簡體   English   中英

http請求在javascript html5音頻預加載時被取消

[英]http request cancelled on javascript html5 audio preload

我正在嘗試用javascript預加載音頻文件。 我正在使用chrome,當我的文件的http請求長大的文件數被chrome取消時...為什么? 我能做什么? 這是我的代碼:

filesToLoad = 44;
filesLoaded = 0;

for ( var ni = 1; ni < filesToLoad; ni++) {

    console.log("start::: " + ServerPath + 'audio/' + ni + '.mp3');
    loadAudio(ServerPath + 'audio/' + ni + '.mp3');
}

function loadAudio(uri) {
    var audio = new Audio();
    audio.addEventListener('canplaythrough', isAppLoaded, true); // It
    audio.src = uri;
    return audio;
}

function isAppLoaded() {
    filesLoaded++;
    if (filesLoaded >= filesToLoad) {
        cb();
    }
    console.log("load::: " + ServerPath + 'audio/' + filesLoaded + '.mp3');
}

function cb() {
    alert("loaded");
}

我試圖做同樣的事情。 我正在預加載12個音頻和12個圖像文件,以便為基於它們的交互式活動做准備。 我遇到了同樣的問題(請求被取消)。

我把這個適用於我的例程放在一起(到目前為止已完成Chrome測試)。

    cacheLessonFiles: function (lessonWords, cacheImg, cacheAudio) {
        var
        fileName = '',
        img = {},
        audio = {},
        wordIDs = Object.keys(lessonWords)
        ;
        wordIDs.forEach(function (wordID) {
            if (cacheImg) {
                fileName = lessonWords[wordID].img || wordID;
                img = new Image();
                img.onload = function () {
                    console.log('cache: finished caching ' + this.src);
                };
                img.src = "/img/" + fileName + imageSuffix;
            }
            if (cacheAudio) {
                fileName = lessonWords[wordID].saySpanish || wordID;
                audio = new Audio();
                audio.onloadeddata = function () {
                    console.log('cache: finished caching ' + this.src);
                };
                audioArray.push({a: audio, f:"/audio/" + fileName + audioSuffix});
            }
        });
        setTimeout(loadAudio, AUDIO_LOAD_WAIT);
    },

該例程只是加載圖像文件而無需特殊處理。 圖像文件比較棘手。 我不是僅為循環中的所有音頻文件設置源,而是使用audio元素和相關的源文件名(.mp3)填充數組。 然后我在超時時啟動了一個自啟動回調來處理數組,在請求之間暫停200ms。

function loadAudio () {
    var
    aud = audioArray.pop()
    ;
    aud.a.src = aud.f;
    if (audioArray.length > 0) {
        setTimeout(loadAudio,  AUDIO_LOAD_WAIT);
    }
}

一個常量和一個變量在閉包內,但在cacheLessonFiles()方法之外。

AUDIO_LOAD_WAIT = 200,
audioArray = []

我嘗試了等待時間少於200毫秒,但取消的請求開始重新出現。

我想,連接速度較慢的客戶端(我在光纖上)可能會再次出現故障,但這對我的目的來說已經足夠好了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM