0
votes

I want to play sound when I click on the image (which I put as a background image in a div), and not playing the sound when my mouse is up.So the sound will only play when mouse is down. But right now, the sound won't stop playing after one-click on the image.

Here is my html for the div:

audio id="audio" src="sound/sound1.mp3" preload="auto"

class="container1" onclick="play()" value="PLAY"

Here is my JavaScript:

function play(){

    var audio = document.getElementById('audio');
    audio.currentTime = 0;

    audio.play();

}

Maybe I should make another function called pause() and use onmouseup="pause()" in HTML? But how to do another function to call this one to stop? I'd love to hear some suggestions. I'm a newbie here. Sorry about the formatting. Thanks!

2

2 Answers

0
votes

use onmousedown and onmouseup events instead of onclick. Add method for pausing audio.

function pause(){
  var audio = document.getElementById('audio')
  audio.pause();
}

after that in your html add events onmousedown="play()" onmouseup="pause()". That should work.

0
votes
imageDivId.addEventListener("mousedown", function () {
//call play function
}, false);
imageDivId.addEventListener("mouseup", function () {
//call pause function
}, false);

Add event listener for mouse event
**imageDivId is used to target element for events
Write two different function for play and pause audio.