暂时解决了安卓和ios不可自动播放的问题。

html代码,用于苹果的音乐播放(苹果有一个开关调静音模式,使用html的audio播放,只要不把音量调到最低,还是可以出声)

<audio id="audio" src="../music.mp3" loop autoplay></audio>
<button id="start">start</button>
<button id="stop">stop</button>
获取html的audio的dom
let htmlAudio = document.querySelector('#audio')
// 这里是AudioContext给安卓用
window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext;

var context = new window.AudioContext();
var source = null;
var audioBuffer = null;

function stopSound() {
    if (source) {
        source.stop(0); //立即停止
    }
}

function playSound() {
    source = context.createBufferSource();
    source.buffer = audioBuffer;
    source.loop = true; //循环播放
    source.connect(context.destination);
    if (!(/iphone/.test(navigator.userAgent.toLowerCase()))) {
        source.start(0); //立即播放

}

function initSound(arrayBuffer) {
    context.decodeAudioData(arrayBuffer, function(buffer) { //解码成功时的回调函数
        audioBuffer = buffer;
        playSound();
    }, function(e) { //解码出错时的回调函数
        console.log('Error decoding file', e);
    });
}

function loadAudioFile(url) {
    var xhr = new XMLHttpRequest(); //通过XHR下载音频文件
    xhr.open('GET', url, true);
    xhr.responseType = 'arraybuffer';
    xhr.onload = function(e) { //下载完成
        initSound(this.response);
    };
    xhr.send();
}
// 安卓,加载并播放
if (!(/iphone/.test(navigator.userAgent.toLowerCase()))) {    
    loadAudioFile('../music.mp3');
}
// 这块是移动端ios自动播放
const invoke = () => {
    if (/iphone/.test(navigator.userAgent.toLowerCase())) {
        if (htmlAudio.paused) {
            htmlAudio.play()
        }
    }
}

if (typeof WeixinJSBridge === 'undefined') {
    document.addEventListener('WeixinJSBridgeReady', () =>
        WeixinJSBridge.invoke('getNetworkType', {}, () => invoke())
    )
}
else {
    WeixinJSBridge.invoke('getNetworkType', {}, () => invoke())
}
// 按钮播放与暂停
$('#start').on('click', function() {
    if (/iphone/.test(navigator.userAgent.toLowerCase())) {
        htmlAudio.play()
    } else {
        playSound()
    }
})
$('#stop').on('click', function() {
    if (/iphone/.test(navigator.userAgent.toLowerCase())) {
        htmlAudio.pause()
    } else {
        stopSound()
    }
})
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐