Detect if audio is playing on macOS

I would like my app to pause currently playing audio (from other applications) for a certain amount of time, and then resume it.

I'm able to simulate the pause/play media key, but the problem is if the system is not playing audio, and then I simulate the key press, it starts playing audio, which is a big no no.

So I need to detect if there is audio playing.

Some things I have explored:
  • kAudioDevicePropertyDeviceIsRunningSomewhere will detect whether is a device running that can play audio, but that doesn't mean it actually is playing audio.

  • AVAudioSession.isOtherAudioPlaying is exactly what I'm looking for, but I'm not working on a Catalyst app, so it's not available to me.

  • I came across this command, but it is not very accurate. If I pause music, it still returns true for the next 30 seconds or so:

Code Block
if [[ "$(pmset -g | grep ' sleep')" == *"coreaudiod"* ]]; then echo audio is playing; else echo no audio playing; fi


Any ideas?

In light of it being WWDC, any Apple Engineers in here that can help? I don't see anything in new APIs

I'm also interested in this, I'd like to be able to detect music playing and pause it for a task, then resume it after. Would you mind sharing how you simulated the play/pause media key?

Detect if audio is playing on macOS
 
 
Q