Quiero poder reproducir y pausar un archivo mp3 con el clic de un solo botón, lo que tengo actualmente reproduce el audio, pero si lo vuelvo a hacer clic no lo detiene.
Por lo que he visto en otras publicaciones, el método que lo hace es audio.pause(), pero no tiene ningún efecto en mi código.
Código:
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="❚❚"; } }Nota: Las líneas que cambian el contenido html funcionan, solo el método audio.pause() no lo hace.
tiia
De acuerdo con la documentación, audio.pause() debería funcionar de la forma en que lo usa. Su problema aquí es que está creando un nuevo elemento de Audio cada vez que se llama playStop() .
En la primera llamada, se crea y reproduce un elemento de audio (que funciona hasta ahora). Pero en la segunda vez, se crea una nueva instancia de un elemento de audio y, de acuerdo con su condición, se detiene directamente donde, como la primera instancia, continuará felizmente reproduciéndose.
// 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 = "❚❚"; } } Para hacer que el código sea más estable, sugiero mejorar su condición if . El objeto audio en sí mantiene la pista ya sea que se esté reproduciendo o no, accesible a través 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(); } }