在HTML中循环播放背景音乐

时间:2020-08-16 04:51:21

标签: javascript html audio

我知道这听起来很简单,我也不知道如何,但是即使半个小时后我也找不到解决方案。 我尝试了很多在网上找到的方法,包括:

<audio loop controls autoplay>
  <source src="music.ogg" type="audio/ogg"/>
  <source src="music.mp3" type="audio/mpeg"/>
  Your browser does not support the audio element.
</audio>
<audio src="music.mp3" autoplay loop>
  <p>If you are reading this, it is because your browser does not support the audio element.</p>
</audio>
<BGSOUND src="All Star.mp3" loop=infinite>
<EMBED src="All Star.mp3" autostart=true loop=true hidden=true>

但是似乎没有任何作用?

2 个答案:

答案 0 :(得分:0)

您可以像这样循环播放: 例如:

audio { display:none;}
<!DOCTYPE html>
<html>
<body>

<h1>The audio loop attribute</h1>

<audio loop autoplay>
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
</audio>

</body>
</html>

这取自w3cschools:https://www.w3schools.com/tags/att_audio_loop.asp

看来您也还没有从w3cshool那里接过,那一个对我有用,所以您应该再尝试一次。

对于Google Chrome,此问题可能会帮助您: How to make audio autoplay on chrome

答案 1 :(得分:0)

我想无论如何这都是浏览器的特定问题,因此您可以在ended事件上为该音频元素添加事件监听器,然后在处理程序中手动进行循环

var audio = document.getElementById('audio_1');
audio.addEventListener('ended', function() {
  loop();
}, false);

function loop() {
  audio.currentTime = 0; //rewind audio track to the beginning
  audio.play(); // play it
}

//also manually trigger play when it is able to play ie. when files is loaded sufficiently for playing
audio.addEventListener('canplay', function() {
  audio.play(); // play it
}, false);
<audio id="audio_1" controls autoplay>
  <source src="https://archive.org/download/cd_inception_hans-zimmer/disc1/12.%20Hans%20Zimmer%20-%20Time_sample.mp3">
</audio>

更新

抱歉,我错过了类似chrome has changed their autoplay policy的内容。因此,尽管循环代码可以正常工作,但是不幸的是,除非自动播放是由用户直接(例如单击该音频播放按钮)或间接(例如在您调用了{{1}的事件处理程序上单击)触发的,否则自动播放可能无法工作})

从Chrome控制台中的此警告可以明显看出这一点 enter image description here