Search code examples
javascriptandroidhtmlmediaelement

Connect HTMLMediaElement to Android playback controls


I have created an HTML audio player in HTML/Javascript for playlists. The playlist is managed internally through a list of media and the ended event automatically plays the next media in line.

From Android Bromite browser, I can play a media and things behave properly. The Android notifications card shows the media playback controls (previous, next, pause), but only the play/pause works.

How could I connect my next/previous Javascript methods (working fine when called from the player HTML buttons) to Android next/previous playback controls ? The HTMLMediaElement API seems to have a audioTracks property that could do it, but it's currently supported by only Safari.


Solution

  • I found it by accident, looking for picture in picture, on https://googlechrome.github.io/samples/picture-in-picture/audio-playlist

    Here is the relevant code :

    let playlist = ... // get your playlist as array
    let audio = new Audio();
    let index = 0;
    
    function switchTrack(index) {
       if(index < 0 && index >= playlist.length) return;
    
       let track = playlist[index];
       audio.src = track.src;
    
       // Update Media Session metadata
       navigator.mediaSession.metadata = new MediaMetadata({
          title: track.title,
          artist: track.artist,
          album: track.album,
          artwork: track.artwork
       });
       audio.play();
    }
    
    navigator.mediaSession.setActionHandler('previoustrack', function() {
      log('> User clicked "Previous Track" button.');
      switchTrack(index - 1);
    });
    
    navigator.mediaSession.setActionHandler('nexttrack', function() {
      log('> User clicked "Next Track" button.');
      switchTrack(index + 1);
    });
    

    More info here : https://developer.mozilla.org/en-US/docs/Web/API/MediaSession