Search code examples
javascriptfunctionvariablesaudiopause

Javascript, pausing audio in function


I have created a game that acts as a showcase for my portfolio.

However I want the audio to pause when a certain function is called

var aud = document.getElementById("#music");

I created a variable that acts as the stand in for the music

function web(i){ 
    aud.pause(); //I try to pause the variable here
    keysPressed = {};
    if (!jumping){$("#guy").css({"background-image":"url(img/Character-Stand.gif)"});}                                          
    window.open(pickup[i].weblink);
};

I don't know what I have done wrong, any help would be appreciated.


Solution

  • Your code doesn't say exactly where you initalize your var aud = document.getElementById("#music"); and also not how you define your audio-tag. But below I have a minimal working example how to pause an audio.

    <html>
    <body>
    <script>
    function pause() {
        var aud = document.getElementById("myAudio");
        aud.pause();
    }
    </script>
    
    <audio id="myAudio" controls>
        <source src="audio.mp3" type="audio/mpeg">
    </audio>
    
    <button onclick="pause()">pause</button>
    </body>
    </html>