首页 > 解决方案 > 音频 .play 方法应该什么时候开始播放音频?

问题描述

当我运行以下...

<audio preload="auto" id="gameFill">
<source src="sounds/gameAttack.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

...

function sleep(ms) {
  date = Date.now();
  currentDate = null;
  do {
    currentDate = Date.now();
  } while (currentDate - date < ms);
}

...

document.getElementById("gameFill").play(); 
console.log("A");
sleep(5000);
console.log("B");

...发生以下情况...

  1. “A”出现在控制台中。
  2. 等待 5 秒。
  3. “B”出现在控制台中。
  4. 声音播放。

为什么在等待 5 秒之前声音没有开始播放?

谢谢,吉姆

标签: javascriptaudio

解决方案


推荐阅读