网络音频 Api - 设置失败 'buffer' 属性

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 函数可访问的范围内,您可以简单地删除缓冲区参数并执行

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                                          
}