Sameen
Sameen

Reputation: 734

How can I resume playing audio from web source after pausing it using HTML5 and JavaScript?

I have some web URLs in tracks array which I'm playing through HTML5 audio API in JavaScript. It pauses when I click on pause. But once paused, when I click on play, the audio starts playing from the beginning.

The HTML spec mentions the audio.currentTime property, so I've tried to track this in a separate variable called currentTime and set it before resuming again, but this does not seem to work as the audio still starts from beginning.

I've spent quite some time on experimenting and Googling, but I can't see what's going wrong here. There's no reason for the audio to not play from where I pause from looking at the logic of this code.

Has anyone else experienced this and know of a workaround?

Here's my js file:

$(function() {
    let trackTitle = $('#title');
    let prevBtn = $('#btn-prev');
    let playPauseBtn = $('#btn-play-pause');
    let nextBtn = $('#btn-next');
    let seekBarFill = $('.seek-bar .fill');

    let tracks = [
        'http://traffic.libsyn.com/minutephysics/Why_You_Should_Care_About_Nukes.mp4?dest-id=95145',
        'http://traffic.libsyn.com/minutephysics/.mp4?dest-id=95145',
        'http://traffic.libsyn.com/minutephysics/Transporters_and_Quantum_Teleportation.mp4?dest-id=95145',
        'http://traffic.libsyn.com/minutephysics/The_Limb_of_the_Sun.mp4?dest-id=95145',
        'http://traffic.libsyn.com/minutephysics/_1.mp4?dest-id=95145',
        'http://traffic.libsyn.com/minutephysics/Concrete_Does_Not_Dry_Out.mp4?dest-id=95145'
    ];
    let audio = new Audio();
    let currentTrack = 0;
    let currentTime = 0;

    function playTrack() {
        audio.src = tracks[currentTrack];
        trackTitle.html('<a href=' + tracks[currentTrack] + '>' + tracks[currentTrack] + '</a>');
        audio.currentTime = currentTime;
        audio.play().then(function() {
            $('#btn-play-pause img').attr('src', 'static/pause.png');
        });
    }

    function playOrPauseTrack() {

        if(audio.paused) {
            console.log('play clicked');
            audio.currentTime = currentTime; // attempted workaround, still not working
            playTrack();
            console.log('play/current time=' + audio.currentTime);
        } else {
            console.log('pause clicked');
            audio.pause();
            currentTime = audio.currentTime;
            console.log('pause/current time=' + currentTime);
            $('#btn-play-pause img').attr('src', 'static/play.png');
        }
    }
});

Upvotes: 1

Views: 3057

Answers (1)

Brad
Brad

Reputation: 163270

When you set the audio element's src property, you reset everything.

Simply don't set it, and don't reset the currentTime. All you have to do is call .play() to resume playing.

Upvotes: 4

Related Questions