2013-09-29 45 views
4

我正在嘗試實現Web Audio API。該代碼適用於Chrome 29.0.1547.76,但不適用於Safari 6.0.5(8536.30.1)。關鍵是我使用noteOn(0)還是start(0)。Safari上是否支持Web Audio API source.start(0)(在Chrome上它工作得很好)?

我想用start()方法,這樣我可以播放聲音的一部分:

asource.start(0, 2, 1); 

在Chrome中工作正常(立即播放,在2秒大關開始,效力於1秒),但是結果在

TypeError: 'undefined' is not a function (evaluating 'asource.start(0, 2, 1)') 

在Safari上。用

代替
asource.noteOn(0); 

工作。 [嗯,我需要調用noteOff(0)而不是stop(0)。]我得到與開始(0)相同的錯誤。那麼,我假設Safari不會實現start(0)?但是如果是這樣,爲什麼HTML5 Rocks中的一些使用start(0)的例子有效?

僅供參考,以下是完整的網頁。我嘗試了很多不同的聲音/格式;都會導致相同的錯誤。

<!DOCTYPE html> 
<html lang=en> 
<head> 
<meta charset="utf-8"> 
<title>Web Audio API Issue</title> 
</head> 
<body> 
<p>Example working on Chrome but not Safari when using start()</p> 

<button id="Load" onclick="init()" >Load</button> 
<button id="Play" onclick="playSound()" disabled>Play</button> 
<button id="Stop" onclick="stopSound()" disabled>Stop</button> 

<script> 
    var web_audio_context; 
    var abuffer; 
    var asource; 

    function init() { 
     contextClass = (window.AudioContext || 
      window.webkitAudioContext || 
      window.mozAudioContext || 
      window.msAudioContext); 
     web_audio_context = new contextClass(); 

     var theURL = './digits.mp3'; 
     var xhr = new XMLHttpRequest(); 
     xhr.open('GET', theURL, true); 
     xhr.responseType = 'arraybuffer'; 
     xhr.onload = function(e) { 
      finishedLoading(this.response); 
     }; 
     xhr.send(); 
    } 

    function finishedLoading(arrayBuffer) { 
     web_audio_context.decodeAudioData(arrayBuffer, function(buffer) { 
      abuffer = buffer; 
      document.getElementById('Load').disabled = true; 
      document.getElementById('Play').disabled = false; 
      document.getElementById('Stop').disabled = false; 
     }, function(e) { 
      console.log('Error decoding file', e); 
     }); 
    } 

    function playSound() { 
     asource = web_audio_context.createBufferSource(); 
     asource.buffer = abuffer; 
     asource.connect(web_audio_context.destination); 
     asource.start(0, 2, 1); 

    } 

    function stopSound() { 
     asource.stop(0); 
    } 
</script> 
</body> 
</html> 
+1

根據https://developer.mozilla.org/en/docs/Web/API/AudioBufferSourceNode的AudioBufferSourceNode有狀態上的Safari瀏覽器 「不明」。 在這種情況下,我想這不是完全實施。 –

+1

Safari 6.1(10月22日發佈)解決了這個問題。該代碼現在可以在Chrome和Safari中使用。 – RPW

回答

4

在較新的Web Audio API版本中,方法noteOn重命名爲start。 Safari仍然使用舊版本,而Chrome使用更新的版本。

試試看:

asource.start ? asource.start(0, 2, 1) : asource.noteOn(0, 2, 1); 
+0

感謝您的建議,但在Safari 6.0.5上,'asource.noteOn(0,2,1)'相當於'asource.noteOn()',即它從頭播放整個聲音,而不是從2秒,並且玩1秒。 – RPW

+0

爲了讓safari和chrome能夠在iOS上運行,我還需要添加以下代碼:asource.stop? asource.stop(0):asource.noteOff(0); – boosth

相關問題