HTML and Javascript audio playlist able to jump tracks via smartphone controls

Viewed 66

I'm creating an HTML audio playlist, everything runs fine, except that I would like the user to be able to jump tracks using smartphones controls (as if he were listening to Spotify), but with this html playlist the use cant jump from tracks via the smartphone controls, instead he can only foward or backward 10secs (as showed in the picture below).

Phone control

Is there anyway to make a html + js playlist that a user can jump tracks from the smartphone control?

Here is the code I am using if its important:

Code

<div class="container">
<div class="large-toggle-btn">
  <i class="large-play-btn"><span class="screen-reader-text">Large toggle button</span></i>
</div>
<!-- /.play-box -->

<div class="info-box">
  <div class="track-info-box">
    <div class="track-title-text"></div>
    <div class="audio-time">
      <span class="current-time">00:00</span> /
      <span class="duration">00:00</span>
    </div>
  </div>
  <!-- /.info-box -->

  <div class="progress-box">
    <div class="progress-cell">
      <div class="progress">
        <div class="progress-buffer"></div>
        <div class="progress-indicator"></div>
      </div>
    </div>
  </div>

</div>
<!-- /.progress-box -->

<div class="controls-box">
  <i class="previous-track-btn disabled"><span class="screen-reader-text">Previous track button</span></i>
  <i class="next-track-btn"><span class="screen-reader-text">Next track button</span></i>
</div>
<!-- /.controls-box -->
<div class="play-list-row" data-track-row="1">
  <div class="small-toggle-btn">
    <i class="small-play-btn"><span class="screen-reader-text">Small toggle button</span></i>
  </div>
  <div class="track-number">
    1.
  </div>
  <div class="track-title">
    <a class="playlist-track" href="#" data-play-track="1">Calexico - Across The Wire</a>
  </div>
</div>
<div class="play-list-row" data-track-row="2">
  <div class="small-toggle-btn">
    <i class="small-play-btn"><span class="screen-reader-text">Small toggle button</span></i>
  </div>
  
1 Answers

This can be achieved with the Media Session API.

Open this demo from a smartphone: https://batman.dev/static/70677190/

<title>Testing</title>
<meta name="viewport" content="width=device-width">

<audio controls />

<script>
  const audio = document.querySelector('audio')
  const tracks = [
    'https://opus-bitrates.anthum.com/audio/hyper/music-96.opus',
    'https://opus-bitrates.anthum.com/audio/music-96.opus',
  ]
  let trackIdx = 0

  audio.src = tracks[trackIdx]

  navigator.mediaSession.setActionHandler('previoustrack', prev)
  navigator.mediaSession.setActionHandler('nexttrack', next)

  function prev() {
    trackIdx--
    playAudio()
  }

  function next() {
    trackIdx++
    playAudio()
  }

  function playAudio() {
    audio.src = tracks[Math.abs(trackIdx % tracks.length)]
    audio.play()
    navigator.mediaSession.playbackState = 'playing'
  }
</script>

Related