2013-08-17 47 views
1

我下面的XMLHttpRequest對象表現得很奇怪,但是我不確定我是否正確使用它。首先,我需要讓每指令located here.XMLHttpRequest'response'參數null

下一頁我的S3服務器上的跨域請求,我的編碼方法.open去我的亞馬遜S3服務器並執行名爲mp3的一個GET「超人」。這似乎沒有錯誤發生,然而這console.log幾行向下

console.log("Current 'request.response' value"); 
console.log(request.response); 

表明request.responsenull。但是..在request.onload函數中,傳入的request.response對象由此console.log語句顯示爲類型AudioBuffer

console.log("Inside 'request.onload' function"); 
    console.log(buffer); 

下面是這兩個語句的控制檯輸出的屏幕截圖。

enter image description here

但是..當我嘗試在.onload方法播放MP3,在屏幕截圖線205下方拋出高亮顯示的錯誤。

enter image description here

我的問題是,我使用XMLHttpRequest對象,並將其正確的功能,如果是這樣,爲什麼我收到此錯誤?我是否需要在.onload方法之前或之後在request.response上運行某種轉換?

var request = new XMLHttpRequest(); 
request.open('GET', 'http://s3.amazonaws.com/tracks/Superman.mp3', true);  
request.responseType = 'arraybuffer'; 

console.log("Current 'request.response' value"); 
console.log(request.response); 

request.onload = function() { 
    context.decodeAudioData(request.response, function(buffer){ 

    console.log("Inside 'request.onload' function"); 
    console.log(buffer); 

    var source = context.createBufferSource(); 
    source.buffer = buffer.byteLength; 
    source.connect(context.destination); 
    source.start(0); 
    } 

回答

1

你分配source.buffer = buffer.byteLength。嘗試source.buffer = buffer

+1

使用此組合並將方法從'.onload()'更改爲'readyStateChanged' – random

1

onloadwindowImage對象。也許你的代碼應該看起來更像是:

var request = new XMLHttpRequest; 
request.open('GET', 'http://s3.amazonaws.com/tracks/Superman.mp3');  
request.responseType = 'arraybuffer'; 
console.log("Current 'request.response' value"); 
console.log(request.response); 
request.onreadystatechange = function(){ 
    if(request.readyState === 4 && request.status === 200){ 
    context.decodeAudioData(request.response, 
     function(buffer){ 
     console.log("Inside 'request.onload' function"); 
     console.log(buffer); 
     var source = context.createBufferSource(); 
     source.buffer = buffer; 
     source.connect(context.destination); 
     source.start(0); 
     } 
    ); 
    } 
} 
+0

從另一個答案中結合使用了這種新方法和'source.buffer = buffer;'。謝謝! – random