Set "currentTime" audio in HTML5

Asked

Viewed 144 times

2

I need to play parts of some songs on 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 it that way, but it doesn’t work.

1 answer

3


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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.