window.AudioContext播放音乐

let sound,audioContext ;
class Sound{
static start(buffer){
        if (!audioContext) {
            window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext || window.oAudioContext;
            audioContext = new window.AudioContext();
            sound.destination = audioContext.destination;
            sound.src = audioContext.createBufferSource();
            if (audioContext.createGain) {
                sound._gain = audioContext.createGain();
            } else {
                sound._gain = audioContext.createGainNode();
            }
            //设置音量
            sound._gain.gain.value = 0.8;
            sound._gain.connect(sound.destination);
        }
        //buffer就是用ajax get方式获取的音乐文件资源
        sound.src.buffer = buffer;
        sound.src.connect(sound._gain);
        //播放
        if (sound.src.start) {
            sound.src.start(0, 0, buffer.duration - 0 - 1.192e-7);
        } else {
            sound.src.noteGrainOn(0, 0, buffer.duration - 0 - 1.192e-7);
        }
        //是否循环
        sound.src.loop = true;
        console.log(sound);
    }
}

好啦,纯js版音乐播放完成

你可能感兴趣的:(window.AudioContext播放音乐)