2

Chrome v6、Safari v7(适用于 v6)

  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.

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

4

1 回答 1

1

Chrome still uses an older webkitAudioContext. This is how I set up context in SoundJS, and it works everywhere:

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

Hope that helps.

于 2013-10-28T15:40:25.510 回答