When I started writing this question, I read a lot of other similar questions on the same topic but still couldn’t find my own answer.
The problem appears when I approach playing audio using “new Audio()” of HTMLAudioElement (Web APIs https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement). Specifically, how to control the running sound that way?
See the following example. If it is not possible to control those running HTMLAudioElements, it will become a disaster for the user. The sounds will overlap and a mess will occur.
The sounds will overlap and a mess will occur.
setTimeout
(
function ()
{
let audio = new Audio("https://www.bensound.com/bensound-music/bensound-dreams.mp3");
audio.autoplay = true;
audio.play()
.then(function ()
{
console.log("Audio 01 is playing.");
})
},
1000 // Audio has a duration of about 2 to 3 minutes
)
setTimeout
(
function ()
{
let audio = new Audio("https://www.bensound.com/bensound-music/bensound-ukulele.mp3");
audio.autoplay = true;
audio.play()
.then(function ()
{
console.log("Audio 02 is playing.");
})
},
5000 // Audio has a duration of about 2 to 3 minutes
)
setTimeout
(
function ()
{
let audio = new Audio("https://www.bensound.com/bensound-music/bensound-creativeminds.mp3");
audio.autoplay = true;
audio.play()
.then(function ()
{
console.log("Audio 03 is playing.");
})
},
10000 // Audio has a duration of about 2 to 3 minutes
)
I know it’s possible to get around that problem by creating an “audio” tag with some identifier, like an id or a class. And so the problem will be solved with a few lines of simple JS.
But what if we have to deal with this problem? Any comments or feedback is highly appreciated. Thanks.