简体   繁体   中英

getting 206 partial content while loading .mp3 files

I have a web app that loads instagram images and creates a slideshow with background sound. While the images are being loaded, a pre loader is run to show the processing. But it doesn't fully load the mp3 file and when I check in the browser's console it has got 206 partial content . So, on clicking the play button, I have to wait a few second so that music is loaded fully to play the slideshow.

 console.log('loading theme: ' + folder);
    $.ajaxSetup({
        cache: false
    });

    $.when(
            $.getScript(epic.getFrontendURL() + "animations/" + folder +  "/js/data.js"),
            $.getScript(epic.getFrontendURL() + "animations/" + folder + "/js/main.js"),
            $.Deferred(function (deferred) {
                $(deferred.resolve);
            })
        ).done(function () {
 //some methods
  sound_bg.src = epic.getFrontendURL() + "sound/back.mp3?
  });

So, is this related somehow, with done which delays the processing.

This behavior is normal. Browsers use HTTP range requests to load audio and video files to minimize bandwidth usage.

If you want the browser to preload the audio, set the preload attribute to auto on the audio element:

<audio src="..." preload="auto"></audio>

I found a way to check if there are errors, if there are sound errors, your website will reload the faulty sound, until it's loaded right. This has worked for me:

var sound1 = new Audio('sfx/1.mp3')
var sound2 = new Audio('sfx/2.mp3')
var sound3 = new Audio('sfx/3.mp3')

var soundChecker = setInterval(function() {
    if (sound1.error) {
        sound1 = new Audio('sfx/1.mp3')
    } else if (sound2.error) {
        sound2 = new Audio('sfx/2.mp3')
    } else if (sound3.error) {
        sound3 = new Audio('sfx/3.mp3')
    } else {
        clearInterval(soundChecker)
    }
}, 1500)

This will check for errors when loading sounds every one and a half seconds (you could modify the time for slower connections), if there is an error with any of the loaded sounds, soundChecker will reload them until all sounds have been loaded successfully (without errors). If all sounds have been loaded successfully the soundChecker interval will clear itself and stop checking.

You will notice that errors such as net::ERR_CACHE_READ_FAILURE 206 (Partial Content) will still be printed in the console but the sound will work, because in a following reload it was successfully loaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM