Is Music Playing on My Computer? How to Check via EXEC on OSX

Our sound system at home consists of a pretty old receiver connect to an OS X mac mini. We often forget to turn the receiver off once music stops playing, and it’s so old it does not have an auto-sleep feature. So it can stay on for days. I wanted a way to check whether the computer is playing music, and if not, turn off the receiver after some time.

I did some reasearch and found out that on OSX, there is a set of sleep parameters that let you know whether sleep is being prevented due to the audio system being in use. You can get those parameters this way on the command line:

 pmset -g 

If sleep is being prevented by sound, you’ll see the word ‘coreaudio’ in the line next to sleep. Therefore, to know if your computer is playing music, you need to execute the following:

 pmset -g | grep -ci coreaudio

This grep command will return 1 if music is playing, and 0 if it’s not.

I then saved this command in a shell script, made it executable, and now I can access the music status via openhab using the EXEC binding, as such:

 String AudioState "Audio Playing [%s]" {exec="<[/users/taj/applications/openhab/configurations/scripts/audiocheck.sh:600000:REGEX((.*?))]",autoupdate="FALSE"}

I now have a value of AudioState = 0 if music is not playing, or AudioState = 1 if music is playing. I can then use that in rules to de-activate a smart switch if music hasn’t been playing say for the last 5 minutes. I can also put a toggle on my UI to allow the smart switch to be turned on by a click.

1 Like

I updated this to be smarter and capable of identifying all applications that are using sound. In the scripts folder, I have the following audiocheck.sh script now:

result1=$(ps -v -e | grep /usr/sbin/coreaudio -m 1 | cut -c 72-72)
result2=$(ps -v -e | grep /usr/sbin/coreaudio -m 1 | cut -c 70-70)
let z=result1+result2*10
if ((z>0)); then
echo “ON”
else
echo “OFF”
fi

Effectively we are looking for the sound power level being output by coreaudio. If any application is using coreaudio, the script will return “ON” otherwise it will return “OFF”

I then have a rule regularly checking the output of this EXEC script and deciding what to do with the power to the receiver.

Here’s an example:

when
Item AudioState changed
then
if (AudioState.state == “ON”) {sendCommand(ZWave_Receiver, “ON”)}
end