首页 > 解决方案 > 为什么不能执行 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();
}

在此处输入图像描述

我还检查了与此问题相关的其他问题,但对我没有任何作用,或者至少我认为如此。我刚开始,我很难弄清楚我需要做什么来解决这个问题。

标签: javascripthtmlcssaudio

解决方案


用户必须首先与 DOM 交互才能播放音频。也许你可以自动点击一些隐藏的元素?

document.body.insertAdjacentHTML('beforeend', '<hidden style="display: none;"></hidden>');
document.querySelector('hidden').click();
// play audio

推荐阅读