Using Multimedia Keys to Change Src

I have an audio tag, and three audio streaming sources.

Currently I have a button for each source, and I change the src using JS, however, I would like to have it so I can change the audio src using the keyboard multimedia keys, the MediaTrackPrevious and MediaTrackNext keys.

Adding a keydown event listener to the document is not helpful, because I want it to work even when the browser is minimized I am on a different tab.

By default the PausePlay multimedia key is working, Is there a way to also make the Previous Next keys work?

Thank you.

Answer

I also have a similar problem which was solved by using media session API.
here is the link

edit: This is the best post I’ve found in media session api and it is as easy as copy paste.

I can’t make comments yet so writing it as an answer.