JSFiddle - React, Tailwind, and code Playground
by oscard
JavaScript
var sounds = [{
id: 1,
name: "sound 1",
path: "https://www.hibou-music.fr/MP3FILES/MELODIC/15_SECONDS/MP3_192/A_PLACE_TO_DREAM_y_bourdin_HIBOU537_LC06881_J2.mp3"
},
{
id: 2,
name: "sound 2",
path: "https://www.hibou-music.fr/MP3FILES/MELODIC/15_SECONDS/MP3_192/BEAUTIFUL_FOR_EVER_A_g_shess_HIB467_LC06881_J1.mp3"
},
{
id: 3,
name: "sound 3",
path: "https://www.hibou-music.fr/MP3FILES/MELODIC/15_SECONDS/MP3_192/BORN_TO_LOVE_B_g_gesina_HIBOU537_LC06881_J1.mp3"
}
];
var autoplayNext = true;
var player = new Audio();
function playSound(sound) {
if (sound.path !== player.currentSrc) {
player.src = sound.path;
}
if (player.paused) {
player.play();
} else {
player.pause();
}
console.log(sound.id);
// play next sound
if (autoplayNext) {
var currentIndex = sounds.findIndex(elemt => elemt.id === sound.id);
player.addEventListener('ended', function () {
currentIndex = parseInt(currentIndex + 1);
var soundToPlayObj = sounds[currentIndex];
if (soundToPlayObj !== undefined && currentIndex <= sounds.length - 1) {
playSound(soundToPlayObj);
} else {
// playSound(sounds[0]);
return;
}
});
}
}
var song = {
id: 1,
name: "sound 1",
path: "https://www.hibou-music.fr/MP3FILES/MELODIC/15_SECONDS/MP3_192/A_PLACE_TO_DREAM_y_bourdin_HIBOU537_LC06881_J2.mp3"
};
playSound(song);