You should wait until the audio file has loaded to apply currentTime
, example:
var audio = new Audio('musica.mp3');
audio.play();
audio.addEventListener('canplay', function() {;
this.currentTime = 15;
this.play();
});
If you want a loop within time you can apply to the event:
audio.addEventListener('canplay', function() {;
this.currentTime = 15;
this.play();
setInterval(function () {
this.currentTime = 15;
this.play();
}.bind(this), 100);
});
Good to remember that your audio should be in the DOM for it to play, for example:
document.body.appendChild(audio);
Take a look at jsfiddle that I did for you.
But if you want to loop your music at a specific time, I do not recommend that you use setInterval
because it will not guarantee the correct effect, in the event that you should use the timeupdate
event then your code would look like this:
audio.addEventListener('canplay', function() {
this.currentTime = 15;
this.play();
});
audio.addEventListener('timeupdate', function() {
if(this.currentTime >= 18) {
this.currentTime = 15;
}
});
setInterval
is a javascript time event that will be fired in a queued manner depending on the availability of the javascript, which can cause it to cut the song later than desired and then sooner behaving well weird. The second example is also available here .