负载&从一组位置名称一次播放多个文件

时间:2012-11-09 09:23:26

标签: javascript web-audio

window.onload = init;

var list = new Array(); //array containing list of music sources
var playListBuffer = new Array(); //array to put in all decoded audio
var playList = new Array();
var context = new webkitAudioContext();

function init(){
    list = ["../media/cello_suit.mp3","../media/morning.mp3"]; //list of files to play at once
    load(list);
}

function load(url){
    for (var i=0; i<list.length; i++){ //load in every url
        var request = new XMLHttpRequest();
        request.open('GET', list[i], true);
        request.responseType = 'arraybuffer';

        request.onload = function () { //Async method
                console.log(request.response);
                context.decodeAudioData(request.response, function(buffer) {    //Async method
                    if (!buffer) {
                        alert('error decoding file data: ');
                        return;
                    }

                    playListBuffer.push(buffer);                                //Decode audio and put inside playListBuffer
                    if (list.length==playListBuffer.length){
                        console.log(playListBuffer);                            //When All files have been decoded show an Array in console
                        prepare();
                    }
                                                                        },  function(e) { console.log('Error decoding audio file', e)});

        };

        request.onerror = function() {
            alert('BufferLoader: XHR error');
        }

        request.send();
    }

}

function prepare(){
    for (var i=0; i<playListBuffer.length; i++){ 
        var source = context.createBufferSource();              // creates a sound source
        console.log(playListBuffer[i]);
        source.buffer = playListBuffer[i];                      // tell the source which sound to play
        source.connect(context.destination);                    // connect the source to the context's destination (the speakers)
        playList.push(source);
    }
    playAll();
}

function playAll(){
    for (var i=0; i<playList.length; i++){ 
        playList[i].noteOn(0); 
    }
}

您好;我在这个使用新的webaudio api的基本脚本上有一些strage行为。此脚本在chrome中引发错误:未捕获错误:SYNTAX_ERR:DOM异常12 audio.js:27 request.onload;但是如果我删除列表中的第二个元素就可以了。为什么呢?

背景信息:此脚本读取一系列歌曲位置并同时播放它们。

1 个答案:

答案 0 :(得分:1)

你需要使用'this',因为变量'request'将在for循环的第二次迭代中被覆盖。

context.decodeAudioData(request.response,
  // ---->
context.decodeAudioData(this.response,