Why can't JavaScript .play() audio files on iPhone safari?

后端 未结 4 1862
慢半拍i
慢半拍i 2020-12-08 06:51

I\'ve got a JavaScript web app working that plays some audio periodically like this:

var SOUND_SUCCESS = new Audio(\'success.mp3\');
SOUND_SUCCESS.play();
         


        
4条回答
  •  天命终不由人
    2020-12-08 07:29

    Haha, i outsmarted it like this.

    Put in the page the audio tag with autoplay (true)

    It will play the sound once the element is mounted. (Even on safari iOS).

    Then it seems you can play it whenever you want again by calling

    document.getElementById('beep').play();
    

    But now you may say, but I don't want to play the sound as autoplay.

    Yes, I outsmarted it to put the "muted" property on that, and then set it to false when playing.

    And play:

    document.getElementById('beep').muted = false;
    document.getElementById('beep').play();
    

提交回复
热议问题