JS使用AudioContext播放音乐

直接通过audio标签播放音乐已经在主流浏览器中不被允许,如下方所示(无论火狐浏览器还是谷歌浏览器中都会报错):

但是我们仍可以通过AudioContext的方式在大部分浏览器中播放音乐,代码如下:

点击查看代码
window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext;
try {
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);
    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();
}
loadAudioFile('../Content/public/mp3/music2.mp3');
$("#stop").click(function() {
    stopSound();
});
} catch (e) {
console.log('!Your browser does not support AudioContext');
}

效果如下(火狐浏览器中可以直接播放出声音来;至少现在在谷歌浏览器中不报错了):

posted @ 2021-12-07 14:12  Lyapeng  阅读(1)  评论(0)    收藏  举报