Search code examples
javascriptaudiopause

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.


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.