Search code examples
javascripthtmlcordovaaudiophonegap

Play sound continuously when button is pressed JavaScript


Is there any way of playing a sound/audio file continuously (using JavaScript) when a button (HTML) is pressed ?

i.e., as long as the button is pressed, the sound plays - once lifted the sound stops.

I've got the sound to play onclick - but obviously it stops after x amount of seconds.

Is there any way to keep it playing until lifted ?

Thanks :)


Solution

  • You can do this like below:

    <button onmousedown="playVid()" onmouseup="pauseVid()" type="button">Play Video</button>
    

    Code snippet:

    var vid = document.getElementById("myVideo"); 
    
    function playVid() { 
       vid.play(); 
    } 
    
    function pauseVid() { 
       vid.pause(); 
    }
    <!DOCTYPE html> 
    <html>
       <body>
          <button onmousedown="playVid()" onmouseup="pauseVid()" type="button">Play Video</button>
          <video id="myVideo" width="320" height="176">
             <source src="mov_bbb.mp4" type="video/mp4">
             <source src="mov_bbb.ogg" type="video/ogg">
             Your browser does not support HTML5 video.
          </video>
          <p>Video courtesy of <a href="https://www.bigbuckbunny.org/" target="_blank">Big Buck Bunny</a>.</p>
       </body>
    </html>

    You can try this with this link.