jQuery--音频处理

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

function testAudio() {
    //浏览器兼容
    window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext || window.oAudioContext;
    var context = new AudioContext(),
        source;
    if (isAndroid == false) {
        $('#mp3').removeClass('rotate-360')
    }
    init();

    function init() {
        //创建XMLhttpRequest对象
        var request = new XMLHttpRequest();
        //使用open方法设置和服务器的交互信息
        request.open('GET', '/assets/byshx2022/source/music.mp3', true);
        //响应类型为 ArrayBuffer
        request.responseType = 'arraybuffer';
        // 异步解码
        request.onload = function() {
            context.decodeAudioData(request.response, function(buffer) {
                //创建一个声音源
                source = context.createBufferSource(); 
                //告诉该源播放何物
                source.buffer = buffer; 
                //将该源与硬件相连
                source.connect(context.destination);
                //循环播放
                source.loop = true;
                //播放
                source.start(0);
            }, function() {});
        }
        request.send();
    }
    //音乐暂停or播放
    $('#mp3').on('click', function() {
        var $actived = $('.swiper-slide-active').eq(0);
        if (context.state == 'suspended') {
            context.resume()
            $('#mp3').addClass('rotate-360');
        } else {
            context.suspend()
            $('#mp3').removeClass('rotate-360');
        }
    });
}
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');
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值