Pyrite/static/pyrite.js
2024-10-29 10:53:46 -04:00

72 lines
1.6 KiB
JavaScript

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);
}
function pauseTrack() {
player.pause();
navigator.mediaSession.playbackState = "paused";
}
function stopTrack() {
player.pause();
player.load();
navigator.mediaSession.playbackState = "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)
});
}