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

主宰稳场 提交于 2019-12-23 22:05:03

问题


I'm modifying a script to play an mp3 that I found on Codepen to get it to work on Safari. In Firefox and Chrome it works fine, but Safari complains : "Unhandled Promise Rejection: TypeError: Not enough arguments index.html:25"

I've read https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/PlayingandSynthesizingSounds/PlayingandSynthesizingSounds.html That goes into much more advanced stuff than I need. I just want to play the sound in my mp3. I need web audio though, because that is the only way to get it to work on iOS Safari.

Does anyone know how to make Safari happy?

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>

回答1:


The Promise-based syntax for BaseAudioContext.decodeAudioData() is not supported in Safari(Webkit). See detailed browser compatibility in the following link

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

So you need to use the old callback syntax as below. It works in both Safari higher than 6.0 and Chrome higher than 10

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


来源:https://stackoverflow.com/questions/48597747/how-to-play-a-sound-file-safari-with-web-audio-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!