[英]Web Audio Api - Fail to set 'buffer' property
我得到以下代碼,用於加載然后在Chrome
瀏覽器上播放.wav
文件:
var songBuffer = null;
// Fix up prefixing
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();
function loadSound(url) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
// Decode asynchronously
request.onload = function() {
context.decodeAudioData(request.response, function(buffer) {
songBuffer = buffer;
});
}
request.send();
}
// Fix up prefixing
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();
function playSound(buffer) {
var source = context.createBufferSource();
// creates a sound source
source.buffer = buffer;
// tell the source which sound to play
source.connect(context.destination);
// connect the source to the context's destination (the speakers)
source.start(0);
// play the source now
}
加載是通過以下方式觸發的: <button onclick="loadSound('audio/sound.wav')">load sound</button>
並且在生成事件時文件加載正常。
並通過以下方式處理播放: <button onclick="playSound()">play sound</button>
。
console.log
告訴我,但是:
Uncaught TypeError: Failed to set the 'buffer' property on 'AudioBufferSourceNode': The provided value is not of type 'AudioBuffer'.
到底是怎么回事?
您沒有將任何內容傳遞給playSound函數,這意味着該行
source.buffer = buffer;
被解釋為
source.buffer = undefined;
由於您的songBuffer變量位於playSound函數可訪問的范圍內,因此您只需刪除buffer參數,然后執行
source.buffer = songBuffer;
因此,要包裝起來-保持原樣,但編輯playSound函數看起來像這樣:
function playSound() {
var source = context.createBufferSource();
// creates a sound source
source.buffer = songBuffer;
// tell the source which sound to play
source.connect(context.destination);
// connect the source to the context's destination (the speakers)
source.start(0);
// play the source now
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.