Set "currentTime" audio in HTML5

2

I need to play parts of some songs in something I'm doing. For example:

var audio = new Audio('musica.mp3');
audio.play();

var interval = setInterval(function() {
    if(audio.currentTime) {
        audio.pause();
        audio.currentTime = 15;
        audio.play();
        clearInterval(interval);
    }
},100);

I tried to do this, but it does not work.

    
asked by anonymous 03.02.2014 / 12:52

1 answer

3

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 .

    
03.02.2014 / 13:06