likes
comments
collection
share

audio.play报错 ,Unhandled Rejection (NotAllowedError

作者站长头像
站长
· 阅读数 15

前景:

框架:使用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()
   

  //这里有个请求
  const isLogin = await getIsLoginAsync().catch(err => {
    setShowLoginDialog(true)
  })
  if (!isLogin) {
     setShowLoginDialog(true)
     return;
  }
 
  //为了兼容iphone
    if (p !== undefined) {
      p.then(() => {
        audioEle.muted = false
        audioEle.pause()
        audioEle.currentTime = 0;
        setTimeout(() => {
          audioEle.play()
        }, 0)
      }).catch((e) => {
        console.log(e)
      })
    }
};

参考:https://juejin.cn/post/684490...这篇文章写的是比较全面,很有参考价值