Saturday, April 27, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  8] [ 0]  / answers: 1 / hits: 23893  / 3 Years ago, thu, august 19, 2021, 7:30:38

I have a dual screen setup on my laptop (using 12.04 LTS) using a HDMI connected display. Everything works fine, but everytime I connect/disconnect the cable I have to go to Sound preferences and change the sound output device manually.



Is there any way to change the sound output device on connect/disconnection of cable, so when I connect my display the sound output is set to HDMI and when I disconnect it the sound goes back to laptop speakers?


More From » 12.04

 Answers
4

I finally managed to make this work using udev. So if someone wants the same behavior here are the steps:



First we need to create a file /etc/udev/rules.d/hdmi_sound.rules with the following content:



    SUBSYSTEM=="drm", ACTION=="change", RUN+="/usr/local/bin/hdmi_sound_toggle"


this will make udev execute the script hdmi_sound_toggle every time there is a change in HDMI connection. That script must have execution permission and the contents are as follows:



#!/usr/bin/env python

import subprocess
from syslog import syslog

def output(cmd):
return subprocess.check_output(cmd, shell=True)

# the following variables may need some modification.
user = "my_username"
card = "/sys/class/drm/card0"
dev_speaker = "output:analog-stereo+input:analog-stereo"
dev_hdmi = "output:hdmi-stereo+input:analog-stereo"
#

interfaces = output("ls {0}".format(card), ).split("
")

vga = filter(lambda x: "VGA" in x, interfaces)[0]
hdmi = filter(lambda x: "HDMI" in x, interfaces)[0]

syslog("HDMI connection was changed!")

hdmi_connected = output("cat {0}/{1}/status".format(card,hdmi)).startswith("connected")
title = "HDMI was {0}".format("connected" if hdmi_connected else "disconnected")
message = "Audio output has changed to {opt}.".format(opt = "HDMI" if hdmi_connected else "built-in speakers")

cmd = "sudo -u " + user + " /usr/bin/pactl set-card-profile 0 " + (dev_hdmi if hdmi_connected else dev_speaker)

syslog("HDMI was connected." if hdmi_connected else "HDMI was disconnected.")
try:
a = output(cmd)
output("sudo -u {0} notify-send "{1}" "{2}"".format(user, title, message))
syslog("Audio output changed.")
except Exception as ex:
syslog("Error changing output device: " + str(ex))


Probably this can be easily made in bash, but as my main language is python I used it. Everything works except the notification: it doesn't show up, I really don't know why. If someone knows how to fix it please say something.



Note: the names of script/udev rule can be changed, but you need to use the full path.


[#32397] Saturday, August 21, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
utschang

Total Points: 357
Total Questions: 120
Total Answers: 119

Location: Croatia
Member since Sat, May 2, 2020
4 Years ago
;