Switching audio between usb DAC and hdmi

The changes you make in dietpi-config are stored at

/boot/dietpi.txt

there is a line:

# Sound card
CONFIG_SOUNDCARD=SOMETHING

For HDMI output it is: “CONFIG_SOUNDCARD=rpi-bcm2835-hdmi”
For USB dac it is: “CONFIG_SOUNDCARD=usb-dac”

I guess you could write a script to change that line and reboot your Pi, bc you have to reboot to make the change happen.


Sometimes you have to use the auto-conversion plugin if you don’t get sound with your USB DAC, but idk where this config is stored, you can enable it also in dietpi-config. (see https://dietpi.com/forum/t/no-audio-from-usb-dac/4996/1)


The script “HDMItoUSB.sh” could look something like:

 #!/bin/bash
 # script to change from HDMI to USB sound
sed -i 's/rpi-bcm2835-hdmi/usb-dac/g' /boot/dietpi.txt
echo "Soundcard changed from HDMI to USB"
echo "machine will reboot in 5 seconds"
sleep 5
reboot

to run the script:

sudo path/to/script/HDMItoUSB.sh

To change from USB to HDMI you just have to change

sed -i 's/rpi-bcm2835-hdmi/usb-dac/g' /boot/dietpi.txt

to

sed -i 's/usb-dac/rpi-bcm2835-hdmi/g' /boot/dietpi.txt

You could even check which soundcard is activated right now and change to the other one, done in one script:

#!/bin/bash
if grep -q CONFIG_SOUNDCARD=rpi-bcm2835-hdmi "/boot/dietpi.txt"; then
    sed -i 's/rpi-bcm2835-hdmi/usb-dac/g' /boot/dietpi.txt
    echo "Soundcard changed from HDMI to USB"
    echo "machine will reboot in 5 seconds"
    sleep 5
    reboot
else
    sed -i 's/usb-dac/rpi-bcm2835-hdmi/g' /boot/dietpi.txt
    echo "Soundcard changed from USB to HDMI"
    echo "machine will reboot in 5 seconds"
    sleep 5
    reboot
fi

I think you have to run the script with root permissions to make changes in /boot/ and to be able to reboot.

These are just theoretical thoughts and this has to be tested! I’m quite new to Linux and scripting stuff and I do not take legal responsibility for anything written here :wink:


ADDENDUM:
You can also output the sound through HDMI and USB simultaneously, says this thread at stackexchange:
https://raspberrypi.stackexchange.com/questions/55593/output-sound-through-hdmi-and-usb-sound-card