2013-10-28 151 views
2

鉻V6,V7的Safari(在V6作品)爲什麼此代碼在Safari中運行,但不是Chrome? Arrrgh

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. 

有誰知道爲什麼會出現這個問題呢?

+0

調用'createBuffer'函數時'request.response'的值究竟是什麼? – Pointy

回答

1

Chrome仍然使用較舊的webkitAudioContext。這是我如何設置上下文SoundJS,和它的作品隨處可見:

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

希望有所幫助。

+0

有趣。如果我添加了這樣的代碼片段,但將這兩行更改爲alert(「Safari」)和alert(「Chrome」),代碼將在兩個瀏覽器中報告「Safari」。 –

+0

我的理解是,Safari現在支持新的AudioContext,並且仍舊不支持webkitAudioContext。 – OJay

相關問題