在linux上手动更改声音输出设备

2024-09-30 22:18:53 发布

您现在位置:Python中文网/ 问答频道 /正文

如果你还没听说过SoundSwitch,它是一款windows应用程序,可以让你用键盘快捷键切换声音输出/输入设备。我已经为linux开发了一个类似的应用程序,但是我不能让它正常工作。应用程序的大部分已经完成,如果您想看到完整的代码,可以在这里:https://github.com/boskobs/sound-Source-Switch-4-Linux 以下是负责应用变更的部分:

   os.system("pacmd set-default-sink " + str(nextindex))
   output = subprocess.getoutput("pacmd list-sink-inputs")
   for item in output.split("\n"):
      if "index:" in item:
         inputindex = item.strip().replace("index: ","")
         os.system("pacmd move-sink-input " + str(inputindex) + " " + str(nextindex))

它会更改默认的声音输出设备,并将所有当前应用程序传输到该设备。当我退出应用程序并切换输出设备时,会出现问题。下一次我启动那个应用程序时,它输出声音的设备就是那个在切换之前处于活动状态的设备。如何使新的默认输出设备真正作为默认输出设备工作?在


Tags: in应用程序声音outputindexositemsystem
2条回答

根据the FreeDesktop.org wiki以及this answer on AskUbuntu和相关帖子,每当一个新的流(声音生成程序)启动时,PulseAudio会将它附加到上次消失时它所连接的同一个接收器(输出设备)。这听起来像你看到的效果。关闭一个使用设备a的程序,启动源代码切换应用程序并将所有内容切换到设备B,然后再次打开该程序,PulseAudio再次将其设置为使用设备a。在

您可以通过添加以下行来禁用PulseAudio的这种行为

load-module module-stream-restore restore_device=false

/etc/pulse/default.pa并重新启动PulseAudio。对于将要使用你的应用程序来管理其声音设备的人来说,这可能是一个合理的选择;您可以将这一点合并到您的安装过程中,但有关在处理系统配置文件时要非常小心的标准建议适用。在

或者,您可以删除存储在文件$HOME/.pulse/*stream-volumes*.gdbm中的流还原数据库。从那时起,PulseAudio将认为每个音频流都是全新的,并将其分配给回退音频设备,这是您用set-default-sink设置的。(这也需要重新启动PA。)

当当前选择的设备与其中一个应用正在流式传输的设备不相同时,将应用修复程序而不是开关。在

   # Checking for changes
   output = subprocess.getoutput("pacmd list-sinks").split("\n")
   for item in range(0, len(output)-1):
      if "* index: " in output[item]:
         currentindexname = output[item+1].replace("name: <", "").strip()[:-1]
         break
   output = subprocess.getoutput("pacmd list-sink-inputs")
   for item in output.split("\n"):
      if "sink:" in item:
         if currentindexname != item.split("<")[1].split(">")[0]:
            for item in output.split("\n"):
               if "index:" in item:
                  inputindex = item.strip().replace("index: ","")
                  os.system("pacmd move-sink-input " + str(inputindex) + " " + str(currentindex))
            os.system('notify-send "Source" "Fixed"')
            exit()

虽然不理想,但它能完成任务。在

相关问题 更多 >