3
votes

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

1 Answers

4
votes

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)
                                              ))