«

使用 AudioContext 播放音频实现 js 播放声音音效文件或自动播放背景音乐,解决谷歌禁止自动播放音频

时间:2024-2-20 11:18     作者:韩俊     分类: Javascript


使用 AudioContext 播放音频实现 js 播放声音音效文件或自动播放背景音乐,解决谷歌禁止自动播放音频。

playAudio('/common/bg.mp3', true);

function playAudio(audio_src, loop) {
    if (typeof loop == 'undefined') {
        loop = false;
    }
    var AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext;
    try {
        var globalBgAudioContext = new AudioContext();
        var source = null;
        var audioBuffer = null;

        function stopSound() {
            if (source) {
                source.stop(0);
            }
        }

        function playSound() {
            source = globalBgAudioContext.createBufferSource();
            source.buffer = audioBuffer;
            source.loop = loop;
            source.connect(globalBgAudioContext.destination);
            source.start(0);
        }

        function initSound(arrayBuffer) {
            globalBgAudioContext.decodeAudioData(arrayBuffer, function (buffer) {
                audioBuffer = buffer;
                playSound();
            }, function (e) {
                console.log('Error decoding file', e);
            });
        }

        function loadAudioFile(url) {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.responseType = 'arraybuffer';
            xhr.onload = function (e) {
                initSound(this.response);
            };
            xhr.send();
        }

        loadAudioFile(audio_src);
        $("#stop").click(function () {
            stopSound();
        });
    } catch (e) {
        console.log('!Your browser does not support AudioContext');
    }

    document.documentElement.addEventListener('mousedown', () => {
        if (globalBgAudioContext.state !== 'running')
            globalBgAudioContext.resume();
    });
}

标签: javascript

热门推荐