To enable audio media playback, you can use the <audio>
element. One method to loop the media playback is by creating an array that contains the paths to the media resources within an object.
When the canplay
event of the <audio>
element occurs, call the .play()
function. At the ended
event, return a resolved Promise
.
Pass the array to the .reduce()
method initialized with a resolved Promise
. Use the .then()
method to call the function again once all media tracks have played.
You can also utilize a Boolean
flag to prevent repeated scheduling of the function that loops the media playback of requested media resources.
const mediaPlaylist = [{
"track": "https://example.com/audio1.mp3",
"title": "Song 1"
}, {
"track": "https://example.com/audio2.mp3",
"title": "Song 2"
}, {
"track": "https://example.com/audio3.mp3",
"title": "Song 3"
}];
const audio = document.querySelector("audio");
const nowPlaying = audio.nextElementSibling;
const mediaTracks = ((promise, {
track,
title
}) =>
promise.then(() => new Promise(resolve => {
audio.src = track;
audio.addEventListener("canplay", event => {
audio.play();
nowPlaying.textContent = title;
}, {
once: true
});
audio.addEventListener("ended", event => {
nowPlaying.textContent = "";
resolve();
}, {
once: true
});
}))
);
let stopMedia = false;
const mediaLoop = (playlist = Array()) =>
!stopMedia
? playlist.reduce(mediaTracks, Promise.resolve())
: Promise.resolve("media loop stopped");
const playMedia = () =>
mediaLoop(mediaPlaylist).then(playMedia);
playMedia()
.then(message => console.log(message))
.catch(err => {console.log(err); throw err});
<audio controls></audio>Now playing: <label></label>