websocket 后台返回MP3音频流,前端实时播放
使用MediaSource API 偶尔在appendBuffer会报错
大佬怎么解啊,这个问题折磨得我头发快掉光了
<audio id="audios"></audio>
const audioPlay = document.getElementById('audios')
const mediaSource = new MediaSource();
let sourceBuffer;
audioPlay.src = window.URL.createObjectURL(mediaSource)
createWebSocket(wsUrl);
mediaSource.addEventListener('sourceopen', () => {
// 给 sourceBuffer 赋值
sourceBuffer = mediaSource.addSourceBuffer('audio/mpeg');
});
var queue = [];
var WS_OnMessage=function(e){
var data=e.data;
if(data instanceof ArrayBuffer) {
if (!sourceBuffer.updating) {
sourceBuffer.appendBuffer(data);
} else {
queue.push(data);
}
sourceBuffer.addEventListener('updateend', function (_) {
if (queue.length > 0) {
sourceBuffer.appendBuffer(queue.shift());
}
if (queue.length === 0 && mediaSource.readyState === 'open') {
mediaSource.endOfStream();
}
audioPlay.play();
});
}
};