I want to pause playback after headphones have been unplugged, then resume after they were plugged back in.
My current solution uses ACPI to detect plug / unplug, as shown here. To play / pause the playback, I use xdotool key XF86AudioPlay
.
This solution works fine in the basic case:
- music is playing, headphones are plugged in
- headphones are unplugged -> music pauses
- headphones are plugged back in -> music continues playing.
However, I do not want to resume playback if it wasn't active when the headphones were unplugged.
Imagine this scenario:
- start up the PC with headphones in,
- play music,
- pause music,
- unplug headphones,
- plug headphones back in.
The last point is where the problem lies – the playback would resume after the headphones are plugged back in, although it was not active at the time they were unplugged.
Moreover, xdotool key XF86AudioPlay
simply toggles the playback, whereas xdotool key XF86AudioPause
does nothing. That makes things even worse:
- start PC with headphones in,
- play music,
- pause music,
- unplug headphones (MUSIC STARTS PLAYING!).
So what I need is to detect play / pause / stop events as well as plug / unplug events, to be able to correctly react in all possible scenarios.
This state machine describes the desired operation:
The one idea that came to my mind is to re-bind the keyboard shortcuts for play / pause / stop to add the state machine logic. This has the drawback that playback always has to be controlled using these keyboard shortcuts, instead of eg. Rhythmbox buttons, which is somewhat impractical.
Also, if I close Rhythmbox while playing, the state machine will stay in a playing
state. Of course I could have a 'daemon' which will wait until Rhythmbox is closed, and then set the state to stopped
. But what if it's not Rhythmbox that plays the music, what if it's for example VLC, etc.? This approach is ugly and unreliable, so I would like to avoid it.
My question: How to detect when media playback was paused / resumed / stopped?