javascript - 为什么不能执行 audio.play(),我查看了检查元素并看到了某种未捕获的错误(承诺中)DOMexception
问题描述
我收到错误消息!
let fillbar=document.querySelector('.fill');
var audios= ["HOTEL_LOBBY.mp3", "FROZEN.mp3", "DOUBLE_UP.mp3"];
let covers=["popsmoke.jpg","2scratch.jpg","ian.jpg"];
let currentTime=document.querySelector(".time");
//Create an Object of Audio
let audio = new Audio();
let currentSong = 0;
// whenever the window load, the song should play automatically
window.onload = playSong;
// let's play the song by this function whenever window load
function playSong() {
audio.src = audios[currentSong];
audio.play();
}
我还检查了与此问题相关的其他问题,但对我没有任何作用,或者至少我认为如此。我刚开始,我很难弄清楚我需要做什么来解决这个问题。
解决方案
用户必须首先与 DOM 交互才能播放音频。也许你可以自动点击一些隐藏的元素?
document.body.insertAdjacentHTML('beforeend', '<hidden style="display: none;"></hidden>');
document.querySelector('hidden').click();
// play audio
推荐阅读
- java - 如何在 IntelliJ IDEA 控制台输出中隐藏命令行?
- r - 我可以按字母顺序使用字母来表示重复的列而不是 R 中的数字吗?
- ruby - 不使用 Enumerable 类或哈希或映射的 Ruby 置换方法代码
- c# - HttpPost 在 ASP.NET MVC 中返回空模型
- angularjs - 错误:[$injector:unpr] 未知提供者:rProvider <- r <- notificationsBarDirective
- python - SQLAlchemy (sqlite3.OperationalError) 没有这样的表:
- python - 如何仅暂停 IF 语句,而不是整个代码 Python
- apache-kafka - Kafka 拓扑设计:如何在超时时加入滑动窗口并发出事件?[难的]
- ruby - bundle install - Gemfile 没有指定依赖项 - 即使我在包含 Gemfile 的目录中
- python - 使方法使用递归选择文件的位置