From 691f266b081a2409385fe1fb09db67a1d4e6ea7d Mon Sep 17 00:00:00 2001 From: Matt Baer Date: Wed, 30 Mar 2022 23:15:23 -0400 Subject: [PATCH] Support MediaSession API - Responds to next / previous track events - Sets metadata for the currently-playing track --- templates/parts.tmpl | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/templates/parts.tmpl b/templates/parts.tmpl index a873151..a63766c 100644 --- a/templates/parts.tmpl +++ b/templates/parts.tmpl @@ -9,7 +9,7 @@
    {{range $i, $el := .}} - {{$el.Artist}} - {{$el.Title}} + {{$el.Artist}} - {{$el.Title}} {{template "track-info" $el}} {{end}} @@ -40,6 +40,10 @@ current = link.parent().index(); play(link, $audio[0]); }); + $audio[0].addEventListener('play', function (e) { + var $link = $('li.active > a'); + setTrackMetadata($link); + }); $audio[0].addEventListener('ended', function (e) { playNext(); }); @@ -70,6 +74,16 @@ play($(link), $audio[0]); } + function setTrackMetadata($link) { + if ('mediaSession' in navigator) { + // Set track metadata + navigator.mediaSession.metadata = new MediaMetadata({ + title: $link.data('title'), + artist: $link.data('artist'), + }); + } + } + function play($link, $player) { $player.src = $link.attr('href'); par = $link.parent(); @@ -77,6 +91,12 @@ $player.load(); $player.play(); } + + if ('mediaSession' in navigator) { + // Listen for MediaSession events + navigator.mediaSession.setActionHandler('nexttrack', playNext); + navigator.mediaSession.setActionHandler('previoustrack', playPrev); + } }); {{end}} \ No newline at end of file