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

标签 javascript ios audio safari web-audio-api

我正在修改一个脚本来播放我在 Codepen 上找到的 mp3,以使其在 Safari 上运行。在 Firefox 和 Chrome 中它工作正常,但 Safari 提示:“未处理的 promise 拒绝: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 的语法。在以下链接中查看详细的浏览器兼容性

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

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

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

关于javascript - 如何使用网络音频 API 播放声音文件 Safari?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48597747/

相关文章:

c - 尝试 portaudio 示例,但得到 "ld: symbol(s) not found for architecture x86_64"

android - 如何最好地确定信号的音量?

javascript - 避免在 raphael.sketchpad 函数中使用 eval

Javascript改变某些数据中的数据

php - 用户输入后更改服务器端的 div 类

objective-c - 在后台呈现一个 View Controller

android - flutter : How to launch the Google Map app with "directions" to a predefined location?

javascript - service-worker `onupdatefound` 未在移动设备上触发

ios - RxSwift 在关闭时正确处理订阅

c++ - 音频设备,更改扬声器设置