Search code examples
javascriptjqueryaudiopause

Playing and Stopping Sound with JS and JQuery


I have a way to play sound with a simple command, https://github.com/admsev/jquery-play-sound, but the audio file I am playing is about 2 minutes long. I need a way to stop/silence the audio with a javascript or jquery command. Does anyone know how I could do this? I don't really want a button that stops the sound unless it was a regular html button that could do other things besides stop the sound.


Solution

  • The jQuery playSound library you linked does not support pausing. I think it would be best to choose a different library that supports pausing so you don’t have to write that functionality yourself.

    I used the howler.js library before and it worked fine for me. Here is how you would use howler.js:

    <!-- to load the library on the page -->
    <script src="howler.js">
    
    // to create and play the sound
    var backgroundMusic = new Howl({
      urls: ['music.mp3', 'music.ogg'],
    }).play();
    
    // to pause the sound
    // (make sure the variable `backgroundMusic` is accessible)
    backgroundMusic.pause();
    
    // to stop the sound
    backgroundMusic.stop();