0
votes

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 :)

1
Use the mousedown event and mouseup event - CertainPerformance
If you're using an <audio> element, you can add the loop attribute, as specified here. Otherwise, please post the relevant source code. - jknotek
Cheers @CertainPerformance - that worked! - pradzr

1 Answers

0
votes

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.