You should wait until the audio file has uploaded to apply the currentTime
, example:
var audio = new Audio('musica.mp3');
audio.play();
audio.addEventListener('canplay', function() {;
this.currentTime = 15;
this.play();
});
Ai if you want a loop within time can apply in 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 him to play, example:
document.body.appendChild(audio);
Take a look at the jsfiddle that I made for you.
But if you want to loop your music at a specific time, I don’t recommend using setInterval
because it will not guarantee the correct effect, in case the ideal is that you use the event timeupdate
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;
}
});
The setInterval
is a javascript time event that will be shot in a row according to the availability of javascript, which can lead him to cut the music later than desired and then earlier getting very strange behavior. The second example is also available here.