Pyrite/static/pyrite.js

81 lines
2.0 KiB
JavaScript
Raw Permalink Normal View History

2024-10-29 10:53:46 -04:00
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);
2024-11-12 13:49:35 -05:00
document.querySelector("#play-btn").style.display = "none";
document.querySelector("#pause-btn").style.display = "initial";
2024-10-29 10:53:46 -04:00
}
function pauseTrack() {
player.pause();
navigator.mediaSession.playbackState = "paused";
2024-11-12 13:49:35 -05:00
document.querySelector("#play-btn").style.display = "initial";
document.querySelector("#pause-btn").style.display = "none";
2024-10-29 10:53:46 -04:00
}
function stopTrack() {
player.pause();
player.load();
navigator.mediaSession.playbackState = "none";
2024-11-12 13:49:35 -05:00
document.querySelector("#play-btn").style.display = "initial";
document.querySelector("#pause-btn").style.display = "none";
2024-10-29 10:53:46 -04:00
}
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)
});
}