我想让浏览器播放我的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();
}

最佳答案

由于autoplay policy

用户需要先与文档进行交互,即单击页面上的某处。



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>





在某个地方放置一个名为“开始游戏”(如果是游戏)的按钮,以便用户在尝试自动播放声音之前先单击您的页面。

10-06 03:11