我一直在尝试跟随一些教程中的步骤,使用按钮和Web Audio API播放简单编码的本地WAV或MP3文件。我的代码如下(testAudioAPI.js):
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();
var myBuffer;
clickme = document.getElementById('clickme');
clickme.addEventListener('click',clickHandler);
var request = new XMLHttpRequest();
request.open('GET', 'WoodeBlock_SMan_B.wav', true);
request.responseType = 'arraybuffer';
// Decode asynchronously
request.onload = function() {
context.decodeAudioData(request.response, function(theBuffer) {
myBuffer = theBuffer;
}, onError);
}
request.send();
function playSound(buffer) {
var source = context.createBufferSource(), g = context.createGain();
source.buffer = buffer;
source.start(0);
g.gain.value = 0.5;
source.connect(g);
g.connect(context.destination);
}
function clickHandler(e) {
playSound(myBuffer);
}
HTML文件将如下所示:
<!doctype html>
<html>
<body>
<button id="clickme">Play</button>
<script src='testAudioAPI.js'></script>
</body>
</html>
然而,完全没有实现任何声音。我尝试了几个片段,但仍然无法弄清楚。当我尝试通过创建振荡器节点合成声音时,确实可以得到声音,但使用来自本地文件的缓冲区时却不行。这里可能出了什么问题?谢谢大家。