前端音频流播放
方式一:
利用js的Api AudioContext来播放:
var AudioContext = window.AudioContext ||
window.webkitAudioContext ||
window.mozAudioContext ||
window.oAudioContext ||
window.msAudioContext;
function playAuido(blob){
var fr = new FileReader();
fr.onload = function () {
var arrBuff = this.result; // ab是转换后的结果
audioContext.decodeAudioData(arrBuff, function (buffer) {
var source = audioContext.createBufferSource();
source.buffer = buffer; // This is the line that generates the error
source.connect(audioContext.destination);
source.start(0);
}
}
fr.readAsArrayBuffer(blob);
}
方式二:
利用auido标签播放:此种方式兼容IE9以上。原理是直接将aduio的src地址指向保存二进制流的内存地址。
function playVideo: function (blob) {
try{
var reader = new FileReader();
reader.onload = function (evt) {
if (evt.target.readyState == FileReader.DONE) {
var data = new Uint8Array(evt.target.result);
indexParam.audio.src = window.URL.createObjectURL(indexMethod.getBlob2(data, data.length));
}
}
reader.readAsArrayBuffer(blob);
} catch (ex) {
console.log(ex);
}
},
function getBlob2: function (data, len) {
var buffer = new ArrayBuffer(len);
var dataview = new DataView(buffer);
dataview = new Uint8Array(data, 0, len);
return new Blob([dataview], { type: 'audio/mp3' });
},
以上两方式接收的必须是流数据才能播放。