1

When the play button is clicked I want the mp3/ogg file to start playing from different randomised points.

There's only one button and no visible player for the user to toggle round. It's meant to be like a radio effect.

I am quite new to javascript so need a bit of help. I think I need to have a bit of code that tells it to skip 10-30s randomly through the file. But not sure how to go about it.

Code here:

<a onclick="javascript:toggleSound();"><li><i class="fa fa-play-circle" aria-hidden="true"></i></li></a>

<audio id="audio" preload="auto">
<source src="audio/filename.mp3" type="audio/mpeg"/>
<source src="audio/filename.ogg" type="audio/ogg"/>

function toggleSound() {
  var audioElem = document.getElementById('audio');
  if (audioElem.paused)
    audioElem.play();
  else
    audioElem.pause();
roserogue
  • 13
  • 3

1 Answers1

0

Try this:

function toggleSound() {
  var audioElem = document.getElementById('audio');
  if (audioElem.paused) {
    audioElem.currentTime = parseInt(Math.random() * 20) + 10;
    audioElem.play();
  }
  else
    audioElem.pause();
}
  • thanks! This seems to jump forward the first time you play-pause-play, but if you do it a second time it starts from the beginning again.Track is 1.30s do you think this is why? – roserogue Jun 02 '17 at 11:47
  • I added this which seems to work audioElem.currentTime = parseInt(Math.random() * 60) + 10; – roserogue Jun 02 '17 at 12:02
  • `parseInt(Math.random() * 20) + 10` should produce a number in the range of 10 to 30. You simply extended the range to 10-70. Not sure how that solves the problem you describe, but as long it works for you :) –  Jun 02 '17 at 13:03
  • maybe extending the range meant that it has more options of intervals to jump so more likely to be random? Probably a flawed theory but it seems to work! – roserogue Jun 07 '17 at 13:33