问题延伸

为了防止恶意使用视频音频,GoogleChrom禁止了自动播放音频的功能,但是视频还是可以的;
不过,IOS微信里添加'WeixinJSBridgeReady'就可以了,安卓需要用户点击下才可以。

解决方案

// html代码
<div id="audio_btn" class="rotate" style="display: block;">
    <audio src="radio/bgm.mp3" id="media" preload="auto" loop="loop">
         <source src="radio/bgm.mp3" type="audio/mpeg">
    </audio>
</div>

// css代码
#audio_btn {
    position: fixed;
    top: 1.2rem;
    right: 1.5rem;
    width: 2rem;
    height: 2rem;
    z-index: 9999;
    background-image: url(../img/Speaker.png);
    background-size: contain;
    background-repeat: no-repeat;
    background-position: center;
    display: none;
}
.rotate {
    -webkit-animation: rotating 1.2s linear infinite;
    -moz-animation: rotating 1.2s linear infinite;
    -o-animation: rotating 1.2s linear infinite;
    animation: rotating 1.2s linear infinite;
}


// 判断兼容ios
function checkIos() {
    var isIOS = /(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent);
    var audio = document.getElementById('media');
    if (isIOS) {
        document.addEventListener("WeixinJSBridgeReady", function () {
            WeixinJSBridge.invoke('getNetworkType', {}, function (e) {
                audio.play();
            });
        }, false);
    }
    if (audio.paused) { audio.play(); }
}

// 音乐播放
function toggleSound() {
    audioPlay = true;
    var audios = document.getElementById('media');
    var audioBtn = document.getElementById('audio_btn');
    audioBtn.addEventListener('touchstart', function (e) {
        if (audioPlay) {
            this.classList.remove('rotate');
            audios.pause();
            audioPlay = false;
        } else {
            this.classList.add('rotate');
            audios.play();
            audioPlay = true;
        }
    })
}