如何在播放过程中使用“ pacmd set-default-sink”更改PulseAudio Sink?


55

我需要切换当前正在播放的音频流的Pulseaudio服务器。

Pulseaudio服务器设置为IP 192.168.1.105

$>cat /etc/pulse/default.pa
...
load-module module-esound-protocol-tcp auth-anonymous=1
load-module module-native-protocol-tcp auth-anonymous=1
load-module module-zeroconf-publish
...

在源方面,VLC媒体播放器正在播放歌曲。

我在源端创建了一个带有Pulseaudio的新隧道接收器。

pacmd load-module module-tunnel-sink server=192.168.1.105
pacmd set-default-sink 1

但是,在播放音频时,无法立即更改服务器。只有停止播放器并重播之后,才可以。

从“ gnome-volume-control”或“ gnome-control-center sound”开始,立即切换输出设备。

在播放声音文件期间,如何立即从命令行应用切换输出接收器?

Answers:


83

pacmd当接收器输入有正在播放的流时,PulseAudio 无法切换默认接收器。但是,仍有一种方法可以实现这一目标。

从命令行更改默认接收器

首先,我们需要确定要切换的接收器的索引号。可以通过调用以下命令来完成:

pacmd list-sinks

根据我们的系统,这将为您提供或多或少的当前可访问的接收器和属性列表:

 >>> 2 sink(s) available.
      * index: 0
            name: <alsa_output.pci-0000_01_00.1.hdmi-stereo-extra1>
            driver: <module-alsa-card.c>
    :
    :
        index: 1
            name: <alsa_output.pci-0000_00_14.2.analog-stereo>
            driver: <module-alsa-card.c>

indexname这里给出的是我们需要通过命令行adressing下沉。当前的默认接收器标有星号(在此处0)。

为了能够从命令行切换默认接收器,我们可能需要通过将相应的行编辑为来禁用流目标设备还原/etc/pulse/default.pa

load-module module-stream-restore restore_device=false

要将默认输出接收器更改为接收器1,然后运行

pacmd set-default-sink 1

可以通过打开“ 声音设置”菜单来可视化成功。

将流移动到另一个接收器

当我们有活动的输入流播放到给定接收器时更改默认接收器无效。宁可通过将此输入移到另一个接收器来完成此操作。

pacmd list-sink-inputs

会告诉我们输入流的索引

>>> 1 sink input(s) available.
    index: 5
    driver: <protocol-native.c>

现在我们知道我们想通过调用将输入流移动5到接收器1

pacmd move-sink-input 5 1

0如果我们愿意,可以沉没。这将立即完成,而无需停止播放。

播放时更改默认接收器

当然,我们可以结合使用这两个命令在播放期间立即切换默认接收器,例如

pacmd set-default-sink 1 & pacmd move-sink-input 5 1

此方法的缺点是,每次我们停止并重新启动音乐播放器时,输入流索引都会更改。因此,在使用命令行进行切换之前,我们始终必须先找出当前的流索引。


您可以通过水槽的索引或名称来引用水槽pactl list short sinks> 4 bluez_sink.FC_A8_9A_2C_EB_0B module-bluez5-device.c s16le 1ch 8000Hz IDLE现在只需引用名称pactl set-default-sink bluez_sink.FC_A8_9A_2C_EB_0B
Leif Liddy

@LeifLiddy:谢谢你的来信。实际上,在最新版本的Pulseaudio中,您确实可以引用接收器的名称,set-default-sink但是您仍将需要使用索引号move-sink-input
塔卡特

如果0 sink input(s) available.呢?但是那个糟糕的Flash Player仍在播放音频吗?
Zhigalin

而且我在client(s) logged inpacmd list
Zhigalin '17

@Zhigalin Flash在我的系统上早已死机,所以我不能说...它可以直接通过ALSA播放。
塔卡特

27

我编写了一个简单的脚本来自动移动所有接收器输入。

用法: ./movesinks.sh <sink number>

#!/bin/bash 
echo "Setting default sink to: $1";
pacmd set-default-sink $1
pacmd list-sink-inputs | grep index | while read line
do
echo "Moving input: ";
echo $line | cut -f2 -d' ';
echo "to sink: $1";
pacmd move-sink-input `echo $line | cut -f2 -d' '` $1

done

1
太棒了!我将其扩展了一些以供自己使用:我希望任务栏上的图标可以在两个声卡之间切换。我用Ruby写了一个小脚本来确定当前接收器,并调出该Shell脚本进行更改(pastebin.com/xb3i2ejW)。之后,我将两个脚本都放在〜/ bin中,并自定义了一个KDE图标来运行ruby脚本。这可以更优雅地完成,也可以完全在shell脚本中完成,但是对我有用。
病原体

2
谢谢你 这是一个切换到最后一个(?-我只有两个)未使用的输出的版本:pastebin.com/raw/sidH7QPb, 即,它切换输出,适合映射到热键。
朱利安

4

@Gaco 脚本的改进版本

#!/usr/bin/env bash

case "${1:-}" in
  (""|list)
    pacmd list-sinks |
      grep -E 'index:|name:'
    ;;
  ([0-9]*)
    echo switching default
    pacmd set-default-sink $1 ||
      echo failed
    echo switching applications
    pacmd list-sink-inputs |
      awk '/index:/{print $2}' |
      xargs -r -I{} pacmd move-sink-input {} $1 ||
        echo failed
    ;;
  (*)
    echo "Usage: $0 [|list|<sink name to switch to>]"
    ;;
esac

我的运行时副本是在github并且它还包括的自动切换主通道kmix



2

我将来自不同地方的东西拼凑在一起,并想出了这个脚本,以在配对后设置蓝牙JAMBOX。您的MAC当然会有所不同。由于我是通过Clementine应用程序控制JAMBOX音量的,因此以我而言,最好的音量是130%。您可能要更改此内容,以及rhythmbox.png(这是我在计算机上可以找到的唯一扬声器图片)。错误检查是基本的,但工作可靠。为了方便起见,我将其放在台式机启动器中。

#!/bin/bash
# setjambox connection setup
# Find the particulars of your environment with 'pactl list sinks'
# This script uses the sink name instead of the index number
# You also need libnotify-bin to run this script

# Enter the bluetooth MAC address of your device here
MAC=00:21:3C:9F:19:AD

# Make ready
# Convert device address per pulseaudio standards
DEV=$(echo $MAC|tr ':' '_')
TITLE="JAMBOX $MAC"
CONNECTED="Audio connection updated."
PROBLEM="Unable to update settings."
JBLOGO=/usr/share/icons/hicolor/48x48/apps/rhythmbox.png

# And go

pactl list short sink-inputs | while read stream; do
    streamId=$(echo $stream | cut '-d ' -f1)
    pactl move-sink-input "$streamId" bluez_sink.$DEV
done

pactl set-default-sink bluez_sink.$DEV
pactl set-card-profile bluez_card.$DEV a2dp
pactl set-sink-volume  bluez_sink.$DEV 130%

if [ $? -eq 0 ]
then
   notify-send -i $JBLOGO -t 3000 "$TITLE" "$CONNECTED" 
else
   notify-send -i gtk-dialog-warning -t 3000 "$TITLE" "$PROBLEM"
fi

+1以使用pactl list short。您可以直接在以下位置进行剪切来简化以下行:pactl list short sink-inputs | cut -f1 | while read streamId对我有用。
bodo '18

1

循环切换沉没。

Gaco脚本仅需一行,即可在可用的接收器之间循环切换。

#!/bin/bash 

new_sink=$(pacmd list-sinks | grep index | tee /dev/stdout | grep -m1 -A1 "* index" | tail -1 | cut -c12-)

echo "Setting default sink to: $new_sink";
pacmd set-default-sink $new_sink
pacmd list-sink-inputs | grep index | while read line
do
echo "Moving input: ";
echo $line | cut -f2 -d' ';
echo "to sink: $new_sink";
pacmd move-sink-input `echo $line | cut -f2 -d' '` $new_sink

done

很棒,简单且可扩展!
Paul Bastian

1

这是一个脚本,也将在接收器之间切换:

http://marginalhacks.com/index.0.html#pulse-switch-out

这是下面的脚本:

#!/usr/bin/ruby
# Filename: pulse-switch-out
# Author:   David Ljung Madison <DaveSource.com>
# See License:  http://MarginalHacks.com/License/
# Description:  Switch pulse audio output (sink) using pacmd

PACMD = %w(pacmd)

##################################################
# Usage
##################################################
def fatal(*msg)
    msg.each { |m| $stderr.puts "[#{$0.sub(/.*\//,'')}] ERROR: #{m}" }
    exit(-1);
end

def usage(*msg)
    msg.each { |m| $stderr.puts "ERROR: #{m}" }
    $stderr.puts <<-USAGE

Usage:  #{$0.sub(/.*\//,'')} [sink]
  Switch sound playback device for ALSA/pulseaudio

    [sink]   Specify sink number to use (see 'pacmd list-sinks')

    USAGE
    exit -1;
end

def parseArgs
    opt = Hash.new
    loop {
        if (arg=ARGV.shift)==nil then break
        elsif arg == '-h' then usage
        elsif arg == '-?' then usage
        #elsif arg == '-arg' then opt[:arg] = true
        elsif arg =~ /^(\d)$/ then opt[:sink] = arg.to_i
        else
            usage("Unknown arg [#{arg}]")
        end
    }

    opt
end

# Unfortunately you can't return or break from the yield without leaving
# the pipe open, maybe use some sort of ensure and figure out how to close?
def pipe(cmd)
        # This is leaving files open
    #IO.popen(cmd.join(' ')).each { |l|
    a = `#{cmd.join(' ')}`
    ret = $?
    a.split("\n").each { |l|
        yield l
    }
    $?
end

def getSinks(ins=false)
    cmd = PACMD.dup
    cmd.push(ins ? 'list-sink-inputs' : 'list-sinks')
    curr = nil
    sinks = Array.new
    pipe(cmd) { |l|
        next unless l=~/\s*(\*)?\s*index:\s+(\d+)/
        i = $2.to_i
        sinks.push(i)
        curr = i if $1
    }
    return sinks,curr
end

##################################################
# Main code
##################################################
def main
    opt = parseArgs

    sinks,curr = getSinks

    usage("No sinks found?") if sinks.empty?
    usage("Only one sink found") if sinks.size==1

    if opt[:sink]
        usage("Unknown sink [#{opt[:sink]}] (out of #{sinks.join(' ')})") unless sinks.index(opt[:sink])
    else
        # Find next sink after curr
        opt[:sink] = sinks[0]
        sinks.each { |s|
            next unless s>curr
            opt[:sink] = s
            break
        }
    end

    # Set default sink
## For some reason this doesn't change the behavior of new apps.
    puts "Set sink: #{opt[:sink]}"
    system("#{PACMD} set-default-sink #{opt[:sink]} > /dev/null")
    usage("Couldn't set default sink [#{opt[:sink]}]") unless $?==0

    # And move all sink-inputs to the new sink
    ins,ignore = getSinks(true)
    ins.each { |i|
        puts "Move playback #{i} to sink #{opt[:sink]}"
        system("#{PACMD} move-sink-input #{i} #{opt[:sink]} > /dev/null")
        usage("Couldn't move playback #{i} to sink [#{opt[:sink]}]") unless $?==0
    }
end
main

1
欢迎来到Ask Ubuntu!虽然从理论上讲这可以回答问题,但最好在此处包括答案的基本部分,并提供链接以供参考。
ζ--

完成,尽管不幸的是,这意味着脚本在这里不会得到更新,除非我记得它在这里。例如,ruby改变了它处理字符串.each的方式(在反引号部分),因此我需要更新上面的第53行。或只是下载脚本以确保它是最新的。
David Ljung Madison Stellar

1

根据Gaco的回答,我将其重写为个人用途。也许有人觉得它有用。用于切换我的USB扬声器和USB游戏耳机。

#!/bin/bash

# get list of sinks/cards (for settings CARD1/CARD2)
# pacmd list-sinks | awk '/name:/ {print $0};' | awk '{ print $2}' | sed 's/<//g; s/>//g'

CARD1="alsa_output.usb-C-Media_INC._C-Media_USB_Audio-00"
CARD2="alsa_output.usb-Kingston_HyperX_Virtual_Surround_Sound_00000000-00"

CURRENT_SINK=$(pacmd stat | awk -F": " '/^Default sink name: /{print $2}' | awk 'BEGIN{FS=OFS="."} NF--' | sed 's/alsa_output/alsa_output/g')


function setCard() {

  if [ "$CURRENT_SINK" == "$1" ]
   then
     echo "Already using this Sink"
     exit 1
  fi

  NEW_SINK=$(pacmd list-sinks | awk '/index:/ {print $1 $2 $3} /name:/ {print $0};' | grep -m1 -B1 $1 | grep index | awk '{print $1}' | cut -d ":" -f2)
  SINK=$(pacmd set-default-sink $NEW_SINK)
  INPUT=$(pacmd list-sink-inputs | grep index | awk '{print $2}')

  pacmd move-sink-input $INPUT $NEW_SINK
  echo "Moving input: $INPUT to sink: $NEW_SINK";
  echo "Setting default sink to: $NEW_SINK";

  notify-send --urgency=low "Audio Switching" "SINK: $NEW_SINK"
}

function toggleSinks() {
  if [ "$CURRENT_SINK" == "$CARD1" ]
    then
      setCard $CARD2
    else
      setCard $CARD1
    fi
}


function showHelp() {
  echo "------------------------------------"
  echo "AUDIO SINK SWITCHER"
  echo " "
  echo "$0 [options]"
  echo " "
  echo "options:"
  echo "-h  --help        What you are looking at.."
  echo "-g, --gaming      Sets Gaming headset as output device"
  echo "-s, --speakers    Sets Speakers as output device"
  echo "-t, --toggle      Toggles the different output devices"
  echo " "
  echo "------------------------------------"
}

# check args length
if [ $# -eq 0 ]
  then
    echo "Toggling output devices (Speakers/Headset)"
    toggleSinks
fi


# arg options
while test $# -gt 0; do
    case "$1" in

                -h|--help)
                        showHelp
                        exit 1
                        ;;

                -g|--gaming)
                        setCard $CARD2
                        exit 1
                        ;;

                -s|--speakers)
                        setCard $CARD1
                        exit 1
                        ;;

                -t|--toggle)
                        toggleSinks
                        echo "Toggling output devices (Speakers/Headset)"
                        exit 1
                        ;;
                 *)
                        showHelp
                        exit 1
                        ;;
    esac
done

0

我认为还有一个值得一提的选项,它可以 在freedesktop.org的官方页面上获得有关PulseAudio的常见问题解答。在以下标题下:

如何切换默认声卡,移动所有应用程序?

他们提供以下脚本来这样做:

#/bin/bash
# paswitch 2011-02-02 by Ng Oon-Ee <ngoonee@gmail.com>
# I can't remember where I found this script, can't locate the original author.
# Please inform me if you know, so that I can give proper attribution.
# CHANGES: Added auto-move all inputs to new default sound card.
# WAS: Pulse Audio Sound Card Switcher v1.0 2010-01-13
#   Switches between soundcards when run. All streams are moved to the new default sound-card.

# $totalsc: Number of sound cards available
totalsc=$(pacmd "list-sinks" | grep card: | wc -l) # total of sound cards: $totalsc
if [ $totalsc -le 1 ]; then # Check whether there are actually multiple cards available
  notify-send -u critical -t 5000 "Nothing to switch, system only has one sound card."
  exit
fi
# $scindex: The Pulseaudio index of the current default sound card
scindex=$(pacmd list-sinks | awk '$1 == "*" && $2 == "index:" {print $3}')
# $cards: A list of card Pulseaudio indexes
cards=$(pacmd list-sinks | sed 's|*||' | awk '$1 == "index:" {print $2}')
PICKNEXTCARD=1 # Is true when the previous card is default
count=0 # count of number of iterations
for CARD in $cards; do
  if [ $PICKNEXTCARD == 1 ]; then
# $nextsc: The pulseaudio index of the next sound card (to be switched to)
    nextsc=$CARD
    PICKNEXTCARD=0
# $nextind: The numerical index (1 to totalsc) of the next card
    nextind=$count
  fi
  if [ $CARD == $scindex ]; then # Choose the next card as default
    PICKNEXTCARD=1
  fi
  count=$((count+1))
done
pacmd "set-default-sink $nextsc" # switch default sound card to next

# $inputs: A list of currently playing inputs
inputs=$(pacmd list-sink-inputs | awk '$1 == "index:" {print $2}')
for INPUT in $inputs; do # Move all current inputs to the new default sound card
  pacmd move-sink-input $INPUT $nextsc
done
# $nextscdec: The device.description of the new default sound card
# NOTE: This is the most likely thing to break in future, the awk lines may need playing around with
nextscdesc=$(pacmd list-sinks | awk '$1 == "device.description" {print substr($0,5+length($1 $2))}' \
                         | sed 's|"||g' | awk -F"," 'NR==v1{print$0}' v1=$((nextind+1)))
notify-send "Default sound-card changed to $nextscdesc"
exit
# Below text was from original author and remains unaltered
# CC BY - creative commons
# Thanks God for help :) and guys lhunath, geirha, Tramp and others from irc #bash on freenode.net

0

我在运行时将@mpapis修改为简单的“ toggle sink0或sink1”:

#!/bin/bash
SINK_INDEX1=0
SINK_INDEX2=1
ACTIVE_SINK=$(pacmd list-sinks | grep '* index:' | grep -o '[0-9]*')
if [ "$ACTIVE_SINK" = $SINK_INDEX1 ] ; then
    pacmd set-default-sink $SINK_INDEX2
    pacmd list-sink-inputs | awk '/index:/{print $2}' | xargs -r -I{} pacmd move-sink-input {} $SINK_INDEX2
else 
    pacmd set-default-sink $SINK_INDEX1
    pacmd list-sink-inputs | awk '/index:/{print $2}' | xargs -r -I{} pacmd move-sink-input {} $SINK_INDEX1
fi
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.