关于javascript:audioplay报错-Unhandled-Rejection-NotAllowedError

8次阅读

共计 1244 个字符,预计需要花费 4 分钟才能阅读完成。

前景:

 框架:应用 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…
这篇文章写的是比拟全面,很有参考价值

正文完
 0