我想让浏览器播放我的wolf.mp3文件十次。加载页面后,没有任何反应。
class Animal {
constructor(name, audioSrc) {
this._name = name;
this._audioSrc = audioSrc;
}
makeSound() {
let audioEl = document.createElement("audio");
audioEl.src = this._audioSrc;
audioEl.autoplay = true;
document.body.appendChild(audioEl);
}
}
let testyWolf = new Animal("wolf","audio/wolf.mp3" );
for (let i = 0; i < 10; i++) {
testyWolf.makeSound();
}
答案 0 :(得分:2)
用户需要先与文档进行交互,即单击页面上的某处。
class Animal {
constructor(name, audioSrc) {
this._name = name;
this._audioSrc = audioSrc;
}
makeSound() {
let audioEl = document.createElement("audio");
audioEl.src = this._audioSrc;
audioEl.autoplay = true;
document.body.appendChild(audioEl);
}
}
let testyWolf = new Animal("wolf","https://freewavesamples.com/files/Yamaha-V50-Rock-Beat-120bpm.wav" );
document.addEventListener('click', e => {
testyWolf.makeSound()
})
<p> Click anywhere </p>
在某个位置放置一个名为“开始游戏”(如果是游戏)的按钮,以便用户在尝试自动播放声音之前先单击您的页面。
答案 1 :(得分:0)
只能播放一个音频文件,但是您可以使一个文件听起来像很多声音。
无论如何,由于autoplay policy.
,如果没有用户与其互动,您将无法自动播放。因此,我对您的代码进行了一些更改,现在当您mouseover
播放主体时,音频将开始播放,尽管看起来像自动播放。看下面了解
class Animal {
constructor(name, audioSrc) {
this._name = name;
this._audioSrc = audioSrc;
this.audioEl= "";
}
play(){
this.audioEl.play();
}
makeSound() {
this.audioEl = document.createElement("audio");
this.audioEl.src = this._audioSrc;
this.audioEl.autoplay = false;
document.body.appendChild(this.audioEl);
return this;
}
}
var items = [];
for (let i = 0; i < 10; i++) {
items.push(new Animal("wolf","https://freewavesamples.com/files/Yamaha-V50-Rock-Beat-120bpm.wav" ).makeSound());
}
document.addEventListener('mouseover', e => {
items.forEach((item)=>
{
setTimeout(function(){ item.play()},200);
});
})