audio
因为audio标签不能自动播放。需要用户和浏览器又交互才能实现播放。但是需求是不能显示播放器控件,只能有声音响起。
AudioContext
使用AudioContext能解决该问题
window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext;
var context = new window.AudioContext();
var source = null;
var audioBuffer = null;
//最好使用本地音频文件,无跨域问题
function playSound() {
source = context.createBufferSource();//获取音频数据
source.buffer = audioBuffer;
source.connect(context.destination);
source.start(); //立即播放
}
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(xxxxxx.mp3)
定时器请求接口获取是否有新订单,有新订单source.start();播放,