Lucas Leal
Lucas Leal

Reputation: 111

How to keep media session notification on chrome android while loading

I've followed this google guide (https://developers.google.com/web/updates/2017/02/media-session) and almost everything works fine. But there is one unwanted behavior: when I change the audio source (either when an audio ends or user click "next track") the notification disappear, and reappear when the audio finished loading and is starting to play. The desired behavior is keep the media notification inbetween tracks. Is there a way to do that?

I've tried setting navigator.mediaSession.playbackState to "playing" but no, no donut for me.

Upvotes: 4

Views: 989

Answers (1)

RuteNL
RuteNL

Reputation: 327

It's probably not relevant anymore, but I've just fixed this in my own music player.

This is the commit that I fixed it in maybe it can help: https://github.com/RuurdBijlsma/VueMusic/commit/c9eff89a2a0bb3ccf360d54c771065d7ce119501

Basically, besides the first audio element variable, I added a second variable called backupAudio, which is only relevant during the switch between audio sources. When I load a new track the backupAudio and audio contents are swapped (the audio becomes backupAudio and the backupAudio becomes audio), after this I set the src on the audio element and pause the backupAudio element.

Doing this ensures the notification works as expected for me. You should be careful with any event listeners you have on the audio elements though. I've previously implemented this in another application where quickly skipping through tracks could cause two tracks to play at the same time, I've fixed that in my current music player. (also don't forget to set volume on both audio elements when changing it like I just did)

Upvotes: 3

Related Questions