前景:
框架:应用umijs比拟全面框架,react栈。问题前景: 对于audio不能自动播放,这里我就不反复了,我的问题就是在iPhone机(v11.3.x)上曾经点击了按钮(和页面交互了), 还是报了 Unhandled Rejection (NotAllowedError): The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.
排查问题:
1.通过一直排查,在交互上audio.play()是没有问题的
如下是失常播放的
<button onClick={() => {clickEgg(1)}}>播放</button> const clickEgg = (index) => { let audioEle = document.getElementById('bg-music') audioEle.play() };
报错状况,很多状况下,咱们须要申请接口再做某个音响播放的。就是这个同步申请就报错了
<button onClick={() => {clickEgg(1)}}>播放</button>let audioEle = document.getElementById('bg-music')const clickEgg = async (index) => { //这里有个申请 const isLogin = await getIsLoginAsync().catch(err => { setShowLoginDialog(true) }) if (!isLogin) { setShowLoginDialog(true) return; } audioEle.play()};
解决问题:
<button onClick={() => {clickEgg(1)}}>播放</button>let audioEle = document.getElementById('bg-music')const clickEgg = async (index) => { audioEle.muted = true let p = audioEle.play() audioEle.currentTime = 0; //这里有个申请 const isLogin = await getIsLoginAsync().catch(err => { setShowLoginDialog(true) }) if (!isLogin) { setShowLoginDialog(true) return; } //为了兼容iphone if (p !== undefined) { p.then(() => { audioEle.muted = false audioEle.pause() setTimeout(() => { audioEle.play() }, 0) }).catch((e) => { console.log(e) }) }};
参考:https://juejin.cn/post/684490...
这篇文章写的是比拟全面,很有参考价值