简体   繁体   English

为什么刷新页面后我的 Javascript 音频不起作用?

[英]Why does my Javascript audio not work after I refresh a page?

I have an audio object in my javascript and a call to the play function.我的 javascript 中有一个音频对象,并调用了播放函数。 It works fine when the I go to the page for the first time or go there through a link from one of my other pages, BUT when I'm on the page with the audio and just want to refresh the page I get audio errors,当我第一次进入该页面或通过我的其他页面中的一个链接进入该页面时它工作正常,但是当我在带有音频的页面上并且只想刷新页面时我收到音频错误,

Uncaught (in promise) DOMException

I have read a post about someone whose audio only works after they refresh it a few times (the opposite of my problem).我读过一篇关于某人的音频仅在刷新几次后才有效的帖子(与我的问题相反)。 And I've read about that error.我已经阅读了有关该错误的信息。 But all I'm trying to do is refresh the page and have things work like they worked the first time.但是我要做的就是刷新页面并让事情像第一次一样工作。

console.log("playing test sound");
let test_sound = new Audio('/static/audio/to-the-point.mp3');
test_sound.play();

This works when I first go to the page, but then gives me that error when I refresh it and the audio doesn't work no matter how many more times I refresh... any ideas?这在我第一次进入页面时有效,但是当我刷新它时给我那个错误并且无论我刷新多少次音频都不起作用......有任何想法吗?

EDIT: upon playing around with it more, the times that the audio gets the error is very inconsistent upon refreshing.编辑:在更多地玩弄它时,音频在刷新时出现错误的次数非常不一致。 Sometimes, the refresh is fine other times it just gets an error.有时,刷新没问题,有时只是出现错误。 Once it gets the error though, subsequent refreshes also get it.一旦它得到错误,随后的刷新也会得到它。 Maybe it's my chrome browser or mac computer?也许是我的 chrome 浏览器或 Mac 电脑?

Upon my own research and help from @Kokodoko it appears that you have to interact with your webpage before audio is allowed.根据我自己的研究和@Kokodoko 的帮助,您似乎必须在允许音频之前与您的网页进行交互。 This is why it worked for me when I came from another page, but failed when I refreshed.这就是为什么当我来自另一个页面时它对我有用,但在我刷新时却失败了。

The solution: make the user interact.解决方案:让用户交互。 Unfortunately, there is no true workaround for letting the audio play before the user has interacted.不幸的是,没有真正的解决方法可以让音频在用户交互之前播放。 Forcing the user to interact in some way before the audio starts, is the only way to get the audio to work强制用户在音频开始之前以某种方式进行交互,是让音频工作的唯一方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM