audio标签播放音频

时间:2023-01-02 00:43:58


H5页面播放音乐其实很简单,只需要用<audio>这个标签就行十分方便。

路径选在音乐所在位置就行了。

<audio  src="js/2.mp3" autoplay preload loop="loop"></audio>

关于点击按钮音乐开启/停止播放的效果做了个简单的例子

<a class="play"  style="cursor:pointer;" οnclick="autoPlay()"></a>
<audio src="js/2.mp3" autoplay preload loop="loop"></audio>
css.pause {
height: 50px;
background: url(images/musicbtn.png) no-repeat;
display: block;
background-position: 0 bottom;
}

.play {
height: 50px;
background: url(images/musicbtn.png) no-repeat;
display: block;
} js
function autoPlay() {
var myAuto = document.getElementById('bgMusic');
var btn = document.getElementById('audioBtn');
if (myAuto.paused) {
myAuto.play();
btn.classList.remove("pause");
btn.classList.add("play");
} else {
myAuto.pause();

btn.classList.remove("play");
btn.classList.add("pause");
}

}

不过只有这个如果是移动端用到,iphone不会开启是自动播放需

<script type="text/javascript">
function audioAutoPlay() {
var audio = document.getElementById("bgMusic"),
play = function () {
audio.play();
document.removeEventListener("touchstart", play, false);
};
audio.play();
document.addEventListener("WeixinJSBridgeReady", function () {
play();
}, false);
document.addEventListener('YixinJSBridgeReady', function () {
play();
}, false);
document.addEventListener("touchstart", play, false);
}
</script>