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

126
Visualizações
Stopping/pausing audio when button is clicked

I want to be able to play and pause an mp3 file on the click of a single button, what I currently have plays the audio, but if I click it again it does not stop it.

By what I've seen on another posts the method that does it is audio.pause(), but it has no effect in my code.

Code:

function playStop(){
                document.getElementById('playControl').style.visibility='visible';
                var audio = new Audio('mp3/audio.mp3');
                
                if (document.getElementById('playbtn').innerHTML=="❚❚"){
                    audio.pause();
                    audio.currentTime = 0;
                    document.getElementById('playbtn').innerHTML="▷";
                }
                else if(document.getElementById('playbtn').innerHTML=="▷"){
                    audio.play();                
                    document.getElementById('playbtn').innerHTML="❚❚";
                }
            }  

Note: The lines that change the html content do work, only the audio.pause() method doesn't.

tyia

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

0

According to documentation the audio.pause() should work the way you use it. Your problem here is that you are creating a new Audio element each time playStop() is called.

On the first call an audio element is created and played (that works so far as) . But on the second time a new instance of an audio element is created and according to your condition it is directly paused where as the first instance will happily continue playing.

fixed code

// have a reference on top level to the "audio" var so it will be 
// correctly played and paused. 
var audio

function playStop() {

    // check wether the audio was already created and do so if not.
    // also create the playcontrol once.
    if (!audio) {
        audio = new Audio('mp3/audio.mp3');
        document.getElementById('playControl').style.visibility = 'visible';
    }

    if (document.getElementById('playbtn').innerHTML == "❚❚") {
        audio.pause();
        // since you only play and pause I do not see the sense behind setting the 
        // currentTime to 0. I will comment it out therefore.
        // audio.currentTime = 0;
        document.getElementById('playbtn').innerHTML = "▷";
    } else if (document.getElementById('playbtn').innerHTML == "▷") {
        audio.play();
        document.getElementById('playbtn').innerHTML = "❚❚";
    }
}

enhanced code

For making the code more stable i suggest to enhance your if condition. The audio object itself holds track wether it is playing or not, accessible via audio.paused

// have a reference on top level to the "audio" var so it will be 
// correctly played and paused. 
var audio

function playStop() {

    // check wether the audio was already created and do so if not.
    // also show the playcontrol on creation.
    if (!audio) {
        audio = new Audio('mp3/audio.mp3');
        document.getElementById('playControl').style.visibility = 'visible';
    }

    // use audio.paused prop for being more consistent. The content of the play button 
    // could be changed without breaking the code now. 
    if (audio.paused) {
        audio.play();
        document.getElementById('playbtn').innerHTML = "❚❚";
    } else {
        document.getElementById('playbtn').innerHTML = "▷";
        audio.pause();
    }

}

docs

  • audio.paused
  • HtmlMediaElement
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