feat: implement audio fade in/out
This commit is contained in:
@@ -1,8 +1,12 @@
|
|||||||
const playBtn = document.getElementById("play-btn");
|
const playBtn = document.getElementById("play-btn");
|
||||||
|
|
||||||
|
const CROSSFADE_DURATION_MS = 5000;
|
||||||
|
const CROSSFADE_INTERVAL_MS = 20;
|
||||||
|
const AUDIO_DURATION_MS = 60000;
|
||||||
|
|
||||||
let isPlaying = false;
|
let isPlaying = false;
|
||||||
let currentAudio;
|
let currentAudio;
|
||||||
let volume = 1;
|
let volume = 0;
|
||||||
|
|
||||||
function playAudio() {
|
function playAudio() {
|
||||||
// add a random query parameter at the end to prevent browser caching
|
// add a random query parameter at the end to prevent browser caching
|
||||||
@@ -15,17 +19,48 @@ function playAudio() {
|
|||||||
isPlaying = false;
|
isPlaying = false;
|
||||||
playBtn.innerText = "play";
|
playBtn.innerText = "play";
|
||||||
};
|
};
|
||||||
|
|
||||||
currentAudio.volume = volume;
|
currentAudio.volume = volume;
|
||||||
|
|
||||||
currentAudio.load();
|
|
||||||
currentAudio.play();
|
currentAudio.play();
|
||||||
|
|
||||||
|
fadeIn();
|
||||||
|
setTimeout(() => {
|
||||||
|
fadeOut();
|
||||||
|
}, AUDIO_DURATION_MS - CROSSFADE_DURATION_MS);
|
||||||
}
|
}
|
||||||
|
|
||||||
function pauseAudio() {
|
function pauseAudio() {
|
||||||
currentAudio.pause();
|
currentAudio.pause();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function fadeIn() {
|
||||||
|
// volume ranges from 0 to 1, this determines by how much the volume number
|
||||||
|
// 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() {
|
||||||
|
// volume ranges from 0 to 1, this determines by how much the volume number
|
||||||
|
// 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);
|
||||||
|
}
|
||||||
|
|
||||||
playBtn.onclick = () => {
|
playBtn.onclick = () => {
|
||||||
if (isPlaying) {
|
if (isPlaying) {
|
||||||
pauseAudio();
|
pauseAudio();
|
||||||
|
Reference in New Issue
Block a user