I have a webapp with multiple audio bubbles, but playing one audio bubble plays audio from the incorrect audio bubble. I'm using: this.audio = new Audio(url). They are interfering in some way. How to solve that?
Ensure all audio objects are accessible to each other and pause them before you start one.
const audioPromises = [
audioFromUrl('https://opus-bitrates.anthum.com/audio/hyper/music-96.opus'),
audioFromUrl('https://opus-bitrates.anthum.com/audio/music-96.opus'),
]
document.querySelectorAll('.play').forEach(el => el.addEventListener('click', () => {
play(parseInt(el.dataset.idx))
}))
document.querySelectorAll('.stop').forEach(el => el.addEventListener('click', stopAll))
async function play(idx) {
const audio = await audioPromises[idx]
await stopAll()
audio.play()
}
function stopAll() {
return Promise.all(audioPromises)
.then(audios => audios.map(audio => audio.pause()))
}
async function audioFromUrl(url) {
const arrayBuffer = await (await fetch(url)).arrayBuffer()
const audio = new Audio()
audio.src = URL.createObjectURL(
new Blob([arrayBuffer])
)
return audio
}
<button class="play" data-idx="0">Play 1</button>
<button class="play" data-idx="1">Play 2</button>
<br /><br />
<button class="stop" data-idx="1">Stop All</button>