У меня была та же проблема, и следующие работали
sudo apt-get install mtp-tools mtpfs
PulseAudio pacmd не может переключать приемники по умолчанию, когда на вход приемника активно воспроизводится поток.
Сначала нам нужно определить номер индекса приемников, которые мы хотим переключить. Это можно сделать, позвонив:
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>
[d4 ] [F10] или name, приведенные здесь, - это то, что нам нужно для адресации раковины по командной строке. Чтобы отключить приемники по умолчанию из командной строки, нам может потребоваться отключить восстановление целевого устройства потока, отредактировав соответствующую строку в [ f13] to:
load-module module-stream-restore restore_device=false
Чтобы изменить выходной приемник по умолчанию на приемник 1, тогда мы запустим
pacmd set-default-sink 1
. Доступность можно визуализировать, открыв меню «Настройки звука». [ ! d8]
Изменение стандартного приемника, когда у нас есть активный входной поток, воспроизводящий данный приемник , отключить восстановление целевого устройства потока . Это нужно сделать, переместив этот вход на другой приемник.
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
Недостатком этого метода является то, что индекс входного потока изменяется каждый раз, когда мы останавливаем и перезапускаем музыкальный проигрыватель. Поэтому нам всегда нужно выяснить текущий индекс потока, прежде чем мы сможем переключиться с помощью линии commmand.
Я написал простой скрипт для автоматического перемещения всех входов-приемников.
Использование: ./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
Существует сценарий ruby (который я изначально разветвлял и переписал разделы), что позволяет изменять значения по умолчанию для стоков, громкости и отключения звука из командной строки.
Улучшенная версия скрипта @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
моя копия времени выполнения @Gaco и включает также автоматическое переключение главного канала для kmix
Я собрал вещи из нескольких разных мест и придумал этот сценарий, чтобы настроить Bluetooth JAMBOX, когда он был спарен. Конечно, ваш MAC будет отличаться. Поскольку я контролирую громкость JAMBOX с помощью приложения Clementine, в моем случае лучше всего работает 130%. Возможно, вы захотите изменить это, наряду с rhythmbox.png (это была единственная фотография, которую я мог найти на своем компьютере). Проверка ошибок является рудиментарной, но работает довольно надежно. Я поместил это в планшетный ПК для удобства на нетбуке ASUS.
#!/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
И вот сценарий, который будет переключаться между приемниками:
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
CIRCLE-TOGGLE SINKS.
Скрипт 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
Я думаю, есть еще один вариант, о котором стоит упомянуть, и он доступен на официальной странице для часто задаваемых вопросов о PulseAudio на freedesktop.org. Под следующим заголовком:
Как переключить звуковую карту по умолчанию, перемещая все приложения?Они предоставляют следующий сценарий для этого:
#/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
Я применил @mpapis к простому «переключению 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
Существует сценарий ruby (который я изначально разветвил и переписал разделы) , который позволяет вам изменять значения по умолчанию для стоков, громкости и отключения звука из командной строки.
Существует сценарий ruby (который я изначально разветвил и переписал разделы) , который позволяет вам изменять значения по умолчанию для стоков, громкости и отключения звука из командной строки.
Я думаю, есть еще один вариант, о котором стоит упомянуть, и он доступен на официальной странице для часто задаваемых вопросов о PulseAudio на freedesktop.org . Под следующим заголовком:
Как переключить звуковую карту по умолчанию, перемещая все приложения?
blockquote>Они предоставляют следующие сценарий для этого:
#/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
Я думаю, есть еще один вариант, о котором стоит упомянуть, и он доступен на официальной странице для часто задаваемых вопросов о PulseAudio на freedesktop.org . Под следующим заголовком:
Как переключить звуковую карту по умолчанию, перемещая все приложения?
blockquote>Они предоставляют следующие сценарий для этого:
#/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
Я написал простой скрипт для автоматического перемещения всех входов-приемников.
Использование: ./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
Я собрал материал из нескольких разных мест и придумал этот скрипт, чтобы настроить Bluetooth JAMBOX, когда он был спарен. Конечно, ваш MAC будет отличаться. Поскольку я контролирую громкость JAMBOX с помощью приложения Clementine, в моем случае лучше всего работает 130%. Возможно, вы захотите изменить это, наряду с rhythmbox.png (это была единственная фотография, которую я мог найти на своем компьютере). Проверка ошибок является рудиментарной, но работает довольно надежно. Я поместил это в планшетный ПК для удобства на нетбуке ASUS.
#!/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