如何使用 Ubuntu 上的脚本在扬声器和 USB 耳机之间切换?

How to change between speakers and USB headset using a script on Ubuntu?

我正在尝试编写一个脚本来在扬声器和耳机之间切换。我希望能够使用快捷方式更改输出和输入。

我使用这些命令来查看我的音频设备:

$ pacmd list-sinks | grep alsa_output 

name: <alsa_output.usb-Logitech_Logitech_USB_Headset-00.analog-stereo>
name: <alsa_output.pci-0000_00_1b.0.analog-stereo>

$ pacmd list-sources | grep alsa_input

name: <alsa_input.usb-Logitech_Logitech_USB_Headset-00.analog-mono>
name: <alsa_input.usb-093a_262c-01.analog-mono>
name: <alsa_input.pci-0000_00_1b.0.analog-stereo>

并编写了这个脚本,以便我可以更改默认音频设备。

#! /bin/bash

  pacmd set-default-sink alsa_output.usb-Logitech_Logitech_USB_Headset-00.analog-stereo
  pacmd set-default-source alsa_input.usb-Logitech_Logitech_USB_Headset-00.analog-mono

exit 0

当我 运行 使用命令

 sudo ./usb-speakers.sh 

我收到了这条消息:

No PulseAudio daemon running, or not running as session daemon.
Home directory not accessible: Permission denied
No PulseAudio daemon running, or not running as session daemon.

我发现了几个有类似问题的问题,但我无法解决任何问题。

https://github.com/mk-fg/pulseaudio-mixer-cli/blob/master/README.md 说:

Kinda like alsamixer, focused not on sink volume levels (which can actually be controlled via alsamixer, with alsa-pulse plugin), but rather on volume of individual streams, so you can turn down the music to hear the stuff from games, mumble, skype or browser.

In addition to interactive UI, script allows to match and configure sink/stream parameters via config file, so that when specific sink or stream appears, e.g. its volume can be capped, port changed, UI title adjusted, be hidden in UI, stuff like that.

我找到了这个脚本(我不记得在哪里了)解决了我所有的问题

#!/bin/bash

declare -i sinks=(`pacmd list-sinks | sed -n -e 's/\**[[:space:]]index:[[:space:]]\([[:digit:]]\)//p'`)
declare -i sinks_count=${#sinks[*]}
declare -i active_sink_index=`pacmd list-sinks | sed -n -e 's/\*[[:space:]]index:[[:space:]]\([[:digit:]]\)//p'`
declare -i next_sink_index=${sinks[0]}

#find the next sink (not always the next index number)
declare -i ord=0
while [ $ord -lt $sinks_count ];
do
echo ${sinks[$ord]}
if [ ${sinks[$ord]} -gt $active_sink_index ] ; then
    next_sink_index=${sinks[$ord]}
    break
fi
let ord++
done

#change the default sink
pacmd "set-default-sink ${next_sink_index}"

#move all inputs to the new sink
for app in $(pacmd list-sink-inputs | sed -n -e 's/index:[[:space:]]\([[:digit:]]\)//p');
do
pacmd "move-sink-input $app $next_sink_index"
done

#display notification
declare -i ndx=0
pacmd list-sinks | sed -n -e 's/device.description[[:space:]]=[[:space:]]"\(.*\)"//p' | while read line;
do
if [ $(( $ord % $sinks_count )) -eq $ndx ] ; then
    notify-send -i notification-audio-volume-high --hint=string:x-canonical-private-synchronous: "Sound output switched to" "$line"
    exit
fi
let ndx++
done;

只需将其复制并粘贴到一个空文档中并另存为 audio-device-swithcer.sh

然后将其保存到您的 usr/local/bin 目录

如果要添加快捷方式,请转至 Keyboard & Shortcuts 并添加新的快捷方式。 作为命令,只需将您的 audio-device-switcher.sh 文件

这就是所有为我工作的人。 并感谢您的回答。