Last active
April 2, 2018 07:34
-
-
Save qtopie/725b6a757123c92d4e6c85173ceeb351 to your computer and use it in GitHub Desktop.
Play Sound script for raspberry pi connected to XiaoMi bluetooth Echo (using a2dp with pulseaudio)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Usage: | |
# bash playsound.sh <AUDIO-FILE> | |
BLUEZ_MAC='74:A3:4A:0F:AB:D3' | |
get_a2dp_sink_index(){ | |
index=$(pactl list sinks short | grep ${BLUEZ_MAC//:/_}.a2dp_sink | awk '{print $1}') | |
echo $index | |
} | |
get_bluez_sink_index() { | |
index=$(pactl list sinks short | grep bluez_sink.${BLUEZ_MAC//:/_} | awk '{print $1}') | |
echo $index | |
} | |
get_bluez_card_index() { | |
index=$(pactl list cards short | grep bluez_card.${BLUEZ_MAC//:/_} | awk '{print $1}') | |
echo $index | |
} | |
count_down_bluez_ready(){ | |
for ((q=10;q>0;q--)); do | |
echo "Counting down ... :$q" | |
echo "Retry connecting to bluetooth device ${BLUEZ_MAC}" | |
echo -e "power on\nconnect ${BLUEZ_MAC}\nquit" | bluetoothctl | |
if ! [[ -z $(get_bluez_card_index) ]]; then | |
echo "bluez card is ready" | |
break | |
fi | |
sleep 5 | |
done | |
} | |
setup_bluez_sink(){ | |
sudo service bluetooth start | |
echo -e "power on\nconnect ${BLUEZ_MAC}\nquit" | bluetoothctl | |
# use a loop to count and check bluez ready | |
count_down_bluez_ready | |
local card_index=$(get_bluez_card_index) | |
pactl set-card-profile ${card_index} a2dp_sink | |
echo "setup bluez sink, index is: $(get_bluez_sink_index)" | |
} | |
switch_to_a2dp() { | |
echo "switch to a2dp" | |
local card_index=$(get_bluez_card_index) | |
pactl set-card-profile ${card_index} a2dp_sink | |
} | |
play_sound(){ | |
echo "Playing sound: $@" | |
paplay -d bluez_sink.${BLUEZ_MAC//:/_}.a2dp_sink "$@" | |
} | |
main() { | |
# check bluez sink ready | |
# if not ready | |
if [[ -z $(get_bluez_sink_index) ]]; then | |
setup_bluez_sink | |
elif [[ -z $(get_a2dp_sink_index) ]]; then | |
switch_to_a2dp | |
fi | |
play_sound "$@" | |
} | |
main "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment