Files
infinifi/web/script.js

93 lines
2.0 KiB
JavaScript
Raw Normal View History

2024-07-20 21:18:41 +01:00
const playBtn = document.getElementById("play-btn");
2024-07-21 00:31:02 +01:00
const catImg = document.getElementsByClassName("cat")[0];
2024-07-20 21:18:41 +01:00
2024-07-20 22:16:16 +01:00
const CROSSFADE_DURATION_MS = 5000;
const CROSSFADE_INTERVAL_MS = 20;
const AUDIO_DURATION_MS = 60000;
2024-07-20 21:18:41 +01:00
let isPlaying = false;
let currentAudio;
2024-07-20 22:16:16 +01:00
let volume = 0;
2024-07-20 21:18:41 +01:00
function playAudio() {
// add a random query parameter at the end to prevent browser caching
currentAudio = new Audio(`/current.mp3?t=${Date.now()}`);
2024-07-20 21:18:41 +01:00
currentAudio.onplay = () => {
isPlaying = true;
playBtn.innerText = "pause";
};
currentAudio.onpause = () => {
isPlaying = false;
volume = 0;
2024-07-20 21:18:41 +01:00
playBtn.innerText = "play";
};
currentAudio.onended = () => {
volume = 0;
playAudio();
};
currentAudio.volume = 0;
2024-07-20 21:18:41 +01:00
currentAudio.play();
2024-07-20 22:16:16 +01:00
fadeIn();
setTimeout(() => {
fadeOut();
}, AUDIO_DURATION_MS - CROSSFADE_DURATION_MS);
2024-07-20 21:18:41 +01:00
}
function pauseAudio() {
currentAudio.pause();
currentAudio.volume = 0;
volume = 0;
2024-07-20 21:18:41 +01:00
}
2024-07-20 22:16:16 +01:00
function fadeIn() {
2024-07-20 22:17:04 +01:00
// volume ranges from 0 to 100, this determines by how much the volume number
2024-07-20 22:16:16 +01:00
// should be incremented at every step of the fade in
const volumeStep = 100 / (CROSSFADE_DURATION_MS / CROSSFADE_INTERVAL_MS);
const handle = setInterval(() => {
volume += volumeStep;
if (volume >= 100) {
clearInterval(handle);
} else {
currentAudio.volume = volume / 100;
}
}, CROSSFADE_INTERVAL_MS);
}
function fadeOut() {
2024-07-20 22:17:04 +01:00
// volume ranges from 0 to 100, this determines by how much the volume number
2024-07-20 22:16:16 +01:00
// should be decremented at every step of the fade out
const volumeStep = 100 / (CROSSFADE_DURATION_MS / CROSSFADE_INTERVAL_MS);
const handle = setInterval(() => {
volume -= volumeStep;
if (volume <= 0) {
clearInterval(handle);
} else {
currentAudio.volume = volume / 100;
}
}, CROSSFADE_INTERVAL_MS);
}
2024-07-21 00:31:02 +01:00
function animateCat() {
let current = 0;
setInterval(() => {
if (current === 3) {
current = 0;
} else {
current += 1;
}
catImg.src = `/images/cat-${current}.png`;
}, 500);
}
2024-07-20 21:18:41 +01:00
playBtn.onclick = () => {
if (isPlaying) {
pauseAudio();
} else {
playAudio();
}
};
2024-07-21 00:31:02 +01:00
animateCat();