为什么此代码在Safari中有效但在Chrome中无效? Arrrgh

时间:2013-10-28 15:07:38

标签: javascript html google-chrome audio safari

Chrome v6,Safari v7(适用于第6版)

  if('AudioContext' in window) {

      var myAudioContext = new AudioContext();            

      const PATH = 'Sounds/',
      SOUNDS = ['Tock08'];
      var soundBuffers = {}, myNodes = {};

      function fetchSounds() {
          var request = new XMLHttpRequest();
          for (var i = 0, len = SOUNDS.length; i < len; i++) {
              request = new XMLHttpRequest();
              request._soundName = SOUNDS[i];
              request.open('GET', PATH + request._soundName + '.aiff', true);
              request.responseType = 'arraybuffer';
              request.addEventListener('load', bufferSound, false);
              request.send();
          }
      }

      function bufferSound(event) {
          var request = event.target;
          var buffer = myAudioContext.createBuffer(request.response, false);
          soundBuffers[request._soundName] = buffer;
      }
  }

  function clickSound() {
      if('AudioContext' in window ) {     //Chrome doesn't work with this or above code
          // create a new AudioBufferSourceNode
          source = myAudioContext.createBufferSource();
          source.buffer = soundBuffers['Tock08'];
          source.loop = false;
          source.connect(myNodes.volume);
          myNodes.volume.gain.value = 1;
          myNodes.volume.connect(myAudioContext.destination);
          source.noteOn(0);               // play right now (0 seconds from now)
       }
  }

在Safari中,一切都很顺利。创建了一个声音缓冲区数组,并且对clickSound的调用会产生令人满意的“点击”。

在Chrome中,情况有所不同。

该行:

var buffer = myAudioContext.createBuffer(request.response, false);

标有

  Uncaught SyntaxError:  An invalid or illegal string was specified.

加载。

然后,如果我打电话给“clickSound”,我得到:

source.buffer = soundBuffers['Tock08'];

Uncaught TypeError: Value is not of type AudioBuffer.

有谁知道为什么会出现这个问题?

1 个答案:

答案 0 :(得分:1)

Chrome仍然使用较旧的webkitAudioContext。这就是我在SoundJS中设置上下文的方式,它可以在任何地方使用:

if (window.webkitAudioContext) {
    s.context = new webkitAudioContext();
} else if (window.AudioContext) {
    s.context = new AudioContext();
}

希望有所帮助。