Determine which application the media keys will control
There was an app (no longer supported) called Media Key Forwarder that allowed users to decide which app would receive the Play/Pause command. Its code is open source.
It wasn't the only one: BeardedSpice also allows users to control the play/pause button behavior, and it's also open source.
I quickly browsed their source codes looking for a specific piece of code to embed here but it was not immediately obvious to me. Nonetheless, I think it's a good start and might help.