Electron - how to control system media (play/pause)?

Viewed 1028

I'm currently building an electron app that has a media control feature. As an example, the touch bar on Mac is able to automatically detect what app is playing audio, and lets you play/pause, skip, and even seek through the audio. This works for Spotify, Quicktime, and even websites in your browser, like a YouTube tab on Google Chrome. Windows also has its own version of this built in to its media controls.

Is there a way for electron to access metadata about the currently playing audio track in the same manner? If not, how can I use the native API to do this? I've tried looking up how to do this in AppleScript, but couldn't find anything.

1 Answers

You can use the Media Session API.

To change the metadata:

navigator.mediaSession.metadata = new MediaMetadata({
    title: "Title",
    artist: "Artist",
    album: "Album",
    artwork: [
        { src: "example.com", sizes: "192x192", type: "image/png" }
    ]
});

Capturing media events:

You can set the callback to null to disable the event, which may gray out the corresponding button.

navigator.mediaSession.setActionHandler("seekto", (seekInfo) => {
    console.log(`seek to ${seekInfo.seekTime} seconds!`)
} });
navigator.mediaSession.setActionHandler("play", () => {} });
navigator.mediaSession.setActionHandler("pause", () => {} });
navigator.mediaSession.setActionHandler("seekbackward", () => {} }); 
navigator.mediaSession.setActionHandler("seekforward", () => {} });
navigator.mediaSession.setActionHandler("previoustrack", () => {} });
navigator.mediaSession.setActionHandler("nexttrack", () => {} });
navigator.mediaSession.setActionHandler("skipad", () => {} });
navigator.mediaSession.setActionHandler("stop", () => {} });
navigator.mediaSession.setActionHandler("togglemicrophone", () => {} });
navigator.mediaSession.setActionHandler("togglecamera", () => {} });
navigator.mediaSession.setActionHandler("hangup", () => {} });

Changing the media duration and if its playing:

navigator.mediaSession.playbackState = "playing";
navigator.mediaSession.playbackState = "paused";

navigator.mediaSession.setPositionState({ position: 30, duration: 60 }) // 0:30 / 1:00

Keep in mind that you need media (sound/video) to have played to have the media controls appear.

Related