var player; var pos_int; function init() { player = document.getElementById('player'); player.addEventListener("ended", nextTrack); navigator.mediaSession.setActionHandler('play', playTrack); navigator.mediaSession.setActionHandler('pause', pauseTrack); navigator.mediaSession.setActionHandler('stop', stopTrack); navigator.mediaSession.setActionHandler('previoustrack', prevTrack); navigator.mediaSession.setActionHandler('nexttrack', nextTrack); pos_int = setInterval(update_position, 300); } async function get_rand_track() { let res = await fetch("./rand_track/") let data = await res.json(); return data; } async function nextTrack() { track = await get_rand_track(); player.src = track.source; playTrack(); } function prevTrack() { // TODO: implement a history array } async function playTrack() { if (!player.src) { return nextTrack(); } player.play(); navigator.mediaSession.playbackState = "playing"; setMediaSession(track); document.querySelector("#play-btn").style.display = "none"; document.querySelector("#pause-btn").style.display = "initial"; } function pauseTrack() { player.pause(); navigator.mediaSession.playbackState = "paused"; document.querySelector("#play-btn").style.display = "initial"; document.querySelector("#pause-btn").style.display = "none"; } function stopTrack() { player.pause(); player.load(); navigator.mediaSession.playbackState = "none"; document.querySelector("#play-btn").style.display = "initial"; document.querySelector("#pause-btn").style.display = "none"; } function setMediaSession(track) { navigator.mediaSession.metadata = new MediaMetadata({ title: track.title, artist: track.artist, album: track.album, artwork: track.artwork }); } function update_position() { if (player.paused){return;} if (player.duration > 0 === false){return;} navigator.mediaSession.setPositionState({ duration: parseInt(player.duration), playbackRate: player.playbackRate, position: parseInt(player.currentTime) }); }