function SetDevice(idx)
  reaper.Main_OnCommand(40099, 0) -- Open audio device preferences
  local window = reaper.JS_Window_Find("REAPER Preferences", true)
  if window ~= nil then
    local arr = reaper.new_array({}, 255)
    local count = reaper.JS_Window_ArrayAllChild(window, arr)
    local adr = arr.table()
  
    for j = 1, #adr do
      local hwnd = reaper.JS_Window_HandleFromAddress(adr[j])
      local id = reaper.JS_Window_GetLong(hwnd, "ID")
      if id == 1000 then
        reaper.JS_WindowMessage_Send(hwnd, "CB_SETCURSEL", idx, 0, 0, 0)
        reaper.JS_WindowMessage_Send(window, "WM_COMMAND", 1144, 0, 0, 0) -- Apply
        reaper.JS_Window_Destroy(window)                                  -- Close window
        break
      end
    end
  end
end

reaper.Main_OnCommand(1016, 0)  -- Transport: Stop
reaper.Main_OnCommand(40099, 0) -- Open audio device preferences
local window = reaper.JS_Window_Find("REAPER Preferences", true)

if window ~= nil then
  local arr = reaper.new_array({}, 255)
  local count = reaper.JS_Window_ArrayAllChild(window, arr)
  local adr = arr.table()

  for j = 1, #adr do
    local hwnd = reaper.JS_Window_HandleFromAddress(adr[j])
    local id = reaper.JS_Window_GetLong(hwnd, "ID")
    if id == 1000 then
      local devices = {}
      local devices_count = reaper.JS_WindowMessage_Send(hwnd, "CB_GETCOUNT", 1, 0, 0, 0)
      local selected = reaper.JS_WindowMessage_Send(hwnd, "CB_GETCURSEL", 0, 0, 0, 0)
      for d = 0, devices_count - 1 do
        reaper.JS_WindowMessage_Send(hwnd, "CB_SETCURSEL", d, 0, 0, 0)
        devices[d + 1] = reaper.JS_Window_GetTitle(hwnd)
      end
      reaper.JS_WindowMessage_Send(hwnd, "CB_SETCURSEL", selected, 0, 0, 0)
      reaper.JS_Window_Destroy(window)
      
      local menu_items = {
        { "#Audio device", nil },
        { "", nil},
      }
      for d = 1, devices_count do
        table.insert(menu_items, { devices[d], d })
      end
      local menu = ""
      for i = 1, #menu_items do
        -- "-2" because we add two entries at the beginning of the menu
        local is_selected = (i - 1 - 2) == selected
        local escaped = menu_items[i][1]
        if i ~= 1 and string.match(escaped, "^[<>!#|]") then
          escaped = " " .. escaped
        end
        if is_selected then
          escaped = "!" .. escaped
        end
        menu = menu .. "|" .. escaped
      end
      gfx.x = gfx.mouse_x - 55
      gfx.y = gfx.mouse_y - 100
      local selection = gfx.showmenu(menu)
      if selection ~= 0 then
        SetDevice(selection - 2)
      end
      gfx.quit()
      break
    end
  end
 end