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

 
更多

使用 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();
    });
}
打赏

本文固定链接: https://www.cxy163.net/archives/3093 | 绝缘体

该日志由 绝缘体.. 于 2023年04月17日 发表在 未分类 分类下, 你可以发表评论,并在保留原文地址及作者的情况下引用到你的网站或博客。
原创文章转载请注明: 使用 AudioContext 播放音频实现 js 播放声音音效文件或自动播放背景音乐,解决谷歌禁止自动播放音频 | 绝缘体
关键字: , , , ,

使用 AudioContext 播放音频实现 js 播放声音音效文件或自动播放背景音乐,解决谷歌禁止自动播放音频:等您坐沙发呢!

发表评论


快捷键:Ctrl+Enter