-3

How to start playback of audio from a specific time point?

let suppose an audio is playing, you reload the page and the audio should resume from that point where the page was reloaded. I already have code storing the time as audio plays, but I don't know how to use that value as new audio start time.

        li = $('#plList li').click(function () {
            var id = parseInt($(this).index());
            if (id !== index) {
                playTrack(id);
            }
        }),

        loadTrack = function (id) {
            $('.plSel').removeClass('plSel');
            $('#plList li:eq(' + id + ')').addClass('plSel');
            npTitle.text(tracks[id].name);
            index = id;
            audio.src = mediaPath + tracks[id].file + extension;

            // Assign an ontimeupdate event to the video element, and execute a function if the current playback position has changed
            audio.ontimeupdate = function() {myFunction()};

            function myFunction() 
            {
                // Display the current position of the audio.
                $('#cookieVal').val(audio.currentTime); 
                localStorage.setItem("audioPlayTime", audio.currentTime);
                console.log(audio.currentTime);
            }
        },

        playTrack = function (id) {
            loadTrack(id);
            audio.play();
        };
    extension = audio.canPlayType('audio/mpeg') ? '.mp3' : audio.canPlayType('audio/ogg') ? '.ogg' : '';
    loadTrack(index);
}
SF.
  • 13,549
  • 14
  • 71
  • 107

2 Answers2

0

You could use currentTime property. Store currentTime in localstorage or cookie.

This question already answered . You can find more detail . Check this out at this link Setting HTML5 audio position

Community
  • 1
  • 1
ToujouAya
  • 593
  • 5
  • 24
0

Hello!

It's really hard to say how to do it without me seeing your code, but I'll give you steps that I would try that could make you achieve this!

note that I am not sure if this is the best way to do this!

1. Use onbeforeunload event to check when user is leaving the page.

2. When this event triggers, save the time and the song to a cookie variable here you can see how

3. And finally use DOMContentLoaded event, so when your page loads, you try to load those variables you saved into cookies.

4. If they exist, you've got your time, just play your song from that time, if not, just start from 0:00.


I'm sorry...

But I can't provide you with ready code, cause you didn't show any either. But I hope that you'll find my answer somewhat useful! Cheers!

Community
  • 1
  • 1
Tomasz Radwaski
  • 202
  • 2
  • 10