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

后端 未结 4 1859
慢半拍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:25

    iOS disables autoplay, instead requiring that play be initiated as part of a user interaction (e.g., you can start playback within a touchstart listener). There's a bit of documentation about this on Apple's developer documentation. There's also this article Overcoming iOS HTML5 audio limitations on IBM's developer site that has examples and more detail.

    0 讨论(0)
  • 2020-12-08 07:26

    To add to xingliang cai's response, here's a code sample I got to work for me:

    const soundEffect = new Audio();
    
    // onClick of first interaction on page before I need the sounds
    soundEffect.play();
    
    // later on when you actually want to play a sound at any point without user interaction
    soundEffect.src = 'path/to/file.mp3';
    soundEffect.play();
    
    0 讨论(0)
  • 2020-12-08 07:27

    IOS on mobile disable automatic sound playing by default. So to get around this problem. You could put enable/disable switch button somewhere on the page and play some sound using an audio element("audioElement") if the user click the button switch.

    After that, the same "audioElement" can be used to play future sounds by changing its "src" attribute and call its "play()" method, without any further user interaction.

    0 讨论(0)
  • 2020-12-08 07:29

    Haha, i outsmarted it like this.

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

    <audio id="beep" src={Assets.SOUND_BEEP} autoPlay />
    

    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.

    <audio id="beep" src={Assets.SOUND_BEEP} autoPlay muted />
    

    And play:

    document.getElementById('beep').muted = false;
    document.getElementById('beep').play();
    
    0 讨论(0)
提交回复
热议问题