user3760628
user3760628

Reputation: 13

play Audio tag onload in a specific time(ogg/mp3) using javascript

Load Audio tag in a specific time(mp3) using javascript. Current code bellow, complety ignores currentTime. My objective is to autoplay a mp3 file based on time(seconds) of the computer hardware clock.

<!DOCTYPE html> 
<html> 
<body> 

<button onclick="setCurTime()" type="button">Set time position to 5 seconds</button>
<br> 


<audio id="audio1"  controls="controls">
  <source src="http://attackbeat.com/audio/Masayume%20Chasing.mp3" type="audio/mp3">

  Your browser does not support HTML5 video.
</audio>

<script>
   var time = new Date();
 var timex = time.getSeconds();
myAudio=document.getElementById("audio1");

window.onload = function () {

myAudio.play();
myAudio.currentTime=10;
}
function setCurTime()
  { 

  myAudio.currentTime=timex;
myAudio.play();
  } 
</script> 
</body> 
</html>

Upvotes: 0

Views: 1732

Answers (1)

Igor Gilyazov
Igor Gilyazov

Reputation: 777

You can seek to the given time only once the meta data is available:

var audio = document.getElementById('audio1');

audio.onloadedmetadata = function() {
  audio.currentTime = new Date().getSeconds(); // autoplay based on current time (seconds)
  audio.play();
};

Upvotes: 1

Related Questions