直接通过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');
}