如何防止“播放()请求被暂停()调用中断"错误? [英] How to prevent "The play() request was interrupted by a call to pause()" error?

查看:32
本文介绍了如何防止“播放()请求被暂停()调用中断"错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个网站,如果用户点击,它会播放声音.为了防止声音重叠,我不得不添加代码:

I made a website where if the user clicks, it plays a sound. To prevent the sound from overlapping, I had to add the code:

n.pause();
n.currentTime = 0;
n.play();

但这会导致错误:play() 请求被调用 pause() 中断
每次触发声音事件后立即出现.声音仍然可以正常播放,但我想防止此错误消息不断弹出.有什么想法吗?

But that causes the error: The play() request was interrupted by a call to pause()
To come up each time the sound event is triggered right after another trigger. The sounds still plays fine, but I want to prevent this error message constantly popping up. Any ideas?

推荐答案

我最近也遇到了这个问题 - 这可能是 play()pause() 之间的竞争条件.看起来有对这个问题的引用,或者相关的这里.

I have encountered this issue recently as well - this could be a race condition between play() and pause(). It looks like there is a reference to this issue, or something related here.

正如 @Patrick 指出的那样,pause 不会返回承诺(或任何东西),所以上述解决方案将不起作用.虽然 MDN 没有关于 pause() 的文档,但在 WC3 媒体元素草案,它说:

As @Patrick points out, pause does not return a promise (or anything), so the above solution won't work. While MDN does not have docs on pause(), in the WC3 draft for Media Elements, it says:

media.pause()

media.pause()

将 paused 属性设置为 true,必要时加载媒体资源.

Sets the paused attribute to true, loading the media resource if necessary.

因此,您还可以检查超时回调中的 paused 属性.

So one might also check the paused attribute in their timeout callback.

基于这个很好的答案,您可以通过以下方法检查视频是否是(或不是)真正播放,因此您可以安全地触发 play() 而不会出错.

Based on this great SO answer, here's a way you can check if the video is (or isn't) truly playing, so you can safely trigger a play() without the error.

var isPlaying = video.currentTime > 0 && !video.paused && !video.ended 
    && video.readyState > video.HAVE_CURRENT_DATA;

if (!isPlaying) {
  video.play();
}

否则,@Patrickanswer 应该可以.

Otherwise, @Patrick's answer should work.

这篇关于如何防止“播放()请求被暂停()调用中断"错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆