Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I want to pause all audios being played with audio.play()

Instead of using the HTML <audio> tag, I’m using my own image of an audio play button:

 <img src="arrow-64.webp" onclick="play('sound-file-1.mp3')"/>
 <img src="arrow-64.webp" onclick="play('intro-file-2.mp3')"/>
 <img src="arrow-64.webp" onclick="play('speech-snippet.mp3')"/>

Here’s the javascript:

function play(x) {
        pauseAll();
        var audio = new Audio(x);
        audio.play();
        }
function pauseAll() {
        var audios = document.getElementsByTagName('play');
        for(var i = 0, len = audios.length; i < len;i++){
                audios[i].pause();
                }
        }

The pauseAll function is supposed to prevent two or more audios from playing at the same time. It doesn’t work, probably because "play" is not a tag name, but I’m not sure how to do this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To achieve what you want, you can use a different approach by storing references to the audio elements in an array and then iterating through that array to pause all the audio elements when needed.

Here’s an updated version of your code:

<img src="arrow-64.webp" onclick="play('sound-file-1.mp3')"/>
<img src="arrow-64.webp" onclick="play('intro-file-2.mp3')"/>
<img src="arrow-64.webp" onclick="play('speech-snippet.mp3')"/>

<script>
var audioElements = [];  // Array to store references to audio elements

function play(x) {
    pauseAll();
    var audio = new Audio(x);
    audioElements.push(audio);  // Add the current audio element to the array
    audio.play();
}

function pauseAll() {
    for (var i = 0, len = audioElements.length; i < len; i++) {
        audioElements[i].pause();
    }
}
</script>

Now, each time you create a new audio element, it is added to the audioElements array. When you call the pauseAll function, it will iterate through this array and pause all the audio elements that have been created.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading