Search code examples
javascriptaudiowebweb-audio-api

preloading the next song in a playlist a bit before the current one ends


I've made a small media player that works fine but I want to make it so that there's no more loading in between each songs

I know about the preload property but it only preloads the music when the page loads for the first time, so I feel like this wont work

is there a way to do this at all? maybe using the web audio API?


Solution

  • When you start playing a song you could watch the play event of the audio and already start preloading the next song in the queue.

    This is the function I use for preloading audio, you can use it any time, not only in the first time the page being loaded:

    function preloadAudio (filename) {
    
        var sound = new Audio();
        sound.preload = 'auto';
    
        sound.addEventListener('canplaythrough', function () {
            // now the audio is ready to play through
        });
    
        document.body.appendChild(sound);
    
        sound.src = filename;
        sound.load();
    
    }