0

I've created a button using an onmousedown event which loops an audio track when clicked. I'm trying to end the audio loop when the same button is clicked. I have tried an onmouseup event but no luck, any ideas? (I'm new to JavaScript)

<script> var one = new Audio(); one.src = "files/audio/one.wav"; one.loop = true; </script>

<img class="item" src="files/button.png" onmousedown="one.play()" onmouseup="one.stop()"/>
Nathan Wilson
  • 169
  • 4
  • 18
  • Try changing `one.stop()` to `one.pause()`, there is not `.stop()` method for audios. https://stackoverflow.com/questions/14834520/html5-audio-stop-function – yuriy636 May 31 '17 at 11:12
  • fyi `onmouseup` is triggered not on second click but on releasing your current click. – NightKn8 May 31 '17 at 11:12

1 Answers1

1

Try using a var to keep track of your clicks and only listen for the click event :

JS

var one = new Audio(); 
one.src = "files/audio/one.wav"; 
one.loop = true;
var isPlaying = false;

function manage(){
  if(isPlaying){
    one.pause();
    one.currentTime = 0;
    isPlaying = false;
  }
  else{
    one.play();
    isPlaying = true;
  }
}

HTML

<img class="item" src="files/button.png" onclick="manage()"/>
Zenoo
  • 12,670
  • 4
  • 45
  • 69
  • Works great, thanks! Now i'm just trying to figure out how to make the audio file restart when clicked again, instead of from it's previous point. I've tried `audio.currentTime = 0` but it doesn't seem to work, maybe i'm using it incorrectly. – Nathan Wilson May 31 '17 at 15:07
  • 1
    You need to use `one.currentTime = 0;`. I edited it in my answer. – Zenoo May 31 '17 at 15:08