Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

150
Visualizações
How to disable or get the HTMLAudioElements being played when they are generated using "new Audio"?

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Consider maintaining a list of all Audio elements created and pause the others when one starts playing:

const GroupedAudio = (() => {
  const audios = []  // all Audio elements created

  return function() {
    const audio = new Audio(...arguments)
    audios.push(audio)
    
    // Pause other Audio when this one starts
    audio.addEventListener('play', () => {
      for (let a of audios) {
        if (a !== audio) {
          a.pause()
        }
      }      
    })

    return audio
  }
})()

const audio1 = new GroupedAudio('https://www.bensound.com/bensound-music/bensound-dreams.mp3')
const audio2 = new GroupedAudio('https://www.bensound.com/bensound-music/bensound-ukulele.mp3')
const audio3 = new GroupedAudio('https://www.bensound.com/bensound-music/bensound-creativeminds.mp3')
<button onclick="audio1.play()">Play 1</button>
<button onclick="audio2.play()">Play 2</button>
<button onclick="audio3.play()">Play 3</button>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda