2014-10-19 136 views
1

我正嘗試在JavaScript中使用Web Audio API將聲音加載到緩衝區並播放它。遺憾的是它不工作,我得到了以下錯誤:JavaScript Web音頻:無法正確解碼音頻數據?

Uncaught TypeError: Failed to set the 'buffer' property on 'AudioBufferSourceNode': 
The provided value is not of type 'AudioBuffer'. 

我可以指出哪些線是給我的錯誤,但我不知道爲什麼。下面是相關的代碼,如果有幫助:

var audioContext; 
var playSoundBuffer; 

function init() { 
    window.AudioContext = window.AudioContext || window.webkitAudioContext; 
    audioContext = new AudioContext(); 

    loadNote(); 
} 

function loadNote() { 
    var request = new XMLHttpRequest(); 
    request.open("GET", "./sounds/topE.wav", true); 
    request.responseType = "arraybuffer"; 
    request.onload = function() { 
     audioContext.decodeAudioData(request.response, function(buffer) { 
      playSoundBuffer = buffer; 
     }, function(error) { 
      console.error("decodeAudioData error", error); 
     }); 
    }; 
    request.send(); 

    playSound(); 
} 

function playSound() { 
    var source = audioContext.createBufferSource(); 
    source.buffer = playSoundBuffer;  // This is the line that generates the error 
    source.connect(audioContext.destination); 
    source.start(0); 
} 

相信decodeAudioData方法返回一個AudioBuffer其第一個回調函數(第二個參數)。我試圖將這個AudioBuffer保存到「playSoundBuffer」然後播放它,但是我得到了這個錯誤,我不知道爲什麼。任何幫助將不勝感激。

回答

6

您得到該錯誤的原因是因爲您忽略了代碼的異步性質,並將它看作是同步的。如果您始終記錄所有相關部分的內容作爲調試的第一步,則您會意識到在您嘗試處理緩衝區時,它是undefined而不是AudioBuffer。提示:總是console.log 所有東西,直到你確切地知道它在任何點的行爲如何。

function loadNote() { 
    var request = new XMLHttpRequest(); 
    request.open("GET", "./sounds/topE.wav", true); 
    request.responseType = "arraybuffer"; 
    request.onload = function() { 
     audioContext.decodeAudioData(request.response, function(buffer) { 
      playSoundBuffer = buffer; 
      playSound(); // don't start processing it before the response is there! 
     }, function(error) { 
      console.error("decodeAudioData error", error); 
     }); 
    }; 
    request.send();//start doing something async 


} 
+1

非常感謝您的回覆!您建議的編輯使聲音播放正常。不幸的是我不太瞭解異步函數是如何工作的。 playSound()方法是否與decodeAudioData方法同時執行?那是什麼造成了錯誤?再次感謝你的幫助! – hashahid 2014-10-19 07:36:17

+2

這裏是一個文章https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests在你的情況下,你實際上在'decodeAudioData'方法之前執行了'playSound()'方法,基本上在您發送請求(即異步)之後,在請求到達之前,以及在您開始對其進行解碼之前(這也是異步) – Winchestro 2014-10-19 07:48:52