为什么 JavaScript .play() 不能在 iPhone Safari 上播放音频文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31776548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:11:18  来源:igfitidea点击:

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

javascriptiosiphoneaudiosafari

提问by Leon Overweel

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

我有一个 JavaScript 网络应用程序可以像这样定期播放一些音频:

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

This works great on desktop browsers (tested in Edge and Chrome), but it doesn't play on Safari on iPhone.

这在桌面浏览器上效果很好(在 Edge 和 Chrome 中测试),但它不能在 iPhone 上的 Safari 上播放。

I've looked around Stack Overflow, and I found some answers from a couple of years ago that it's not possible to play audio from Safari unless you're in that full screen player. Is this still the case?

我环顾了 Stack Overflow,几年前我找到了一些答案,除非您在全屏播放器中,否则无法从 Safari 播放音频。现在还是这样吗?

回答by Ed Ballot

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 limitationson IBM's developer site that has examples and more detail.

iOS 禁用自动播放,而是要求将播放作为用户交互的一部分启动(例如,您可以在 touchstart 侦听器中开始播放)。Apple's developer documentation上有一些关于此的文档。IBM 的开发人员站点上还有这篇文章克服 iOS HTML5 音频限制,其中包含示例和更多详细信息。

回答by user2415116

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

要添加到 xingliang cai 的回复中,这是我必须为我工作的代码示例:

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

回答by xingliang cai

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.

移动设备上的 IOS 默认禁用自动声音播放。所以要解决这个问题。如果用户单击按钮开关,您可以将启用/禁用开关按钮放在页面上的某个位置并使用音频元素(“ audioElement”)播放一些声音。

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.

之后,可以使用相同的“ audioElement”通过更改其“ src”属性并调用其“ play()”方法来播放未来的声音,而无需任何进一步的用户交互。