如何使用网络音频 API 播放声音文件 Safari?

How to play a sound file Safari with web audio API?

我正在修改一个脚本来播放我在 Codepen 上找到的 mp3,以使其在 Safari 上运行。在 Firefox 和 Chrome 它工作正常,但 Safari 抱怨:“未处理的承诺拒绝:TypeError:没有足够的参数 index.html:25

我读过 https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/PlayingandSynthesizingSounds/PlayingandSynthesizingSounds.html 它比我需要的更高级。我只想播放我的 mp3 中的声音。不过我需要网络音频,因为这是让它在 iOS Safari 上运行的唯一方法。

有谁知道如何使 Safari 快乐?

https://codepen.io/kslstn/full/pagLqL

(function () {
    
  if('AudioContext' in window || 'webkitAudioContext' in window) {  
    // Check for the web audio API. Safari requires the webkit prefix.


  const URL = 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/123941/Yodel_Sound_Effect.mp3';
    
  var AudioContext = window.AudioContext || window.webkitAudioContext;
  var context = new AudioContext(); // Make it crossbrowser    
      
  const playButton = document.querySelector('#play');
    
  let yodelBuffer;

  window.fetch(URL)
    .then(response => response.arrayBuffer())
    .then(arrayBuffer => context.decodeAudioData(arrayBuffer))
    .then(audioBuffer => {
      yodelBuffer = audioBuffer;
    });
    
    playButton.onclick = () => play(yodelBuffer);

  function play(audioBuffer) {
    const source = context.createBufferSource();
    source.buffer = audioBuffer;
    source.connect(context.destination);
    source.start();
  }

}

}());
<button id="play">Yodel!</button>

Safari(Webkit) 不支持 BaseAudioContext.decodeAudioData() 基于 Promise 的语法。请参阅以下 link

中详细的浏览器兼容性

https://developer.mozilla.org/en-US/docs/Web/API/BaseAudioContext/decodeAudioData

因此您需要使用如下旧的回调语法。它适用于高于 6.0 的 Safari 和高于 Chrome 高于 10

的 Safari
window.fetch(URL)
  .then(response => response.arrayBuffer())
  .then(arrayBuffer => context.decodeAudioData(arrayBuffer, 
                                               audioBuffer => {
                                                 yodelBuffer = audioBuffer;
                                                }, 
                                               error => 
                                               console.error(error)
                                              ))