本文主要是介绍腾讯tts获取文件blob推流解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
方案1,获取推流拼接到数据,播放时将 Blob 转换为 URL,把audioUrl赋值给
ws.onmessage((res) => {// console.log('onmessage res.data',res.data)if (typeof res.data == "object") {blobs.value.push(res.data);const newBolb = new Blob([...blobs.value], { type: "audio/mp3" });// 将 Blob 转换为 URLaudioUrl.value = URL.createObjectURL(newBolb);}// console.log('onmessage audioUrl.value',audioUrl.value)});
<audio ref="audioPlayer" controls><source :src="audioUrl" type="audio/mpeg" autoplay />Your browser does not support the audio element.
</audio>
方案二,实现边推流边播放(不稳定)
ws.onmessage((res) => {if (typeof res.data == "object") {appendBuffer(res.data);} else {}});const appendBuffer = (blob) => {const reader = new FileReader();reader.onload = () => {const arrayBuffer = reader.result;if (sourceBuffer && !sourceBuffer.updating && !audioPlayer.value.error ) {sourceBuffer.appendBuffer(arrayBuffer);}};reader.readAsArrayBuffer(blob);
};const onSourceOpen = () => {if (!sourceBuffer) {sourceBuffer = mediaSource.addSourceBuffer('audio/mpeg');sourceBuffer.addEventListener('updateend', () => {// 当 sourceBuffer 更新结束时,可以继续追加数据if (ws && ws.readyState === WebSocket.OPEN) {ws.onmessage((res) => {if (typeof res.data == "object") {appendBuffer(res.data);}});}});}
};
方案3 (推荐)
let mediaSource = new MediaSource();
let sourceBuffer;
let queue = [];
let isUpdating = false;const audioPlayer = document.getElementById('audioPlayer'); // Assume you have an <audio> element with this id
audioPlayer.src = URL.createObjectURL(mediaSource);const appendBuffer = (blob) => {const reader = new FileReader();reader.onload = () => {const arrayBuffer = reader.result;queue.push(arrayBuffer);processQueue();};reader.readAsArrayBuffer(blob);
};const processQueue = () => {if (queue.length > 0 && !isUpdating && sourceBuffer && !audioPlayer.error) {const buffer = queue.shift();isUpdating = true;sourceBuffer.appendBuffer(buffer);}
};const onSourceOpen = () => {if (!sourceBuffer) {sourceBuffer = mediaSource.addSourceBuffer('audio/mpeg');sourceBuffer.mode = 'sequence'; // Ensure the buffer is appended in sequencesourceBuffer.addEventListener('updateend', () => {isUpdating = false;processQueue(); // Continue processing the queue after each update});}
};mediaSource.addEventListener('sourceopen', onSourceOpen);ws.onmessage = (res) => {if (typeof res.data === 'object') {appendBuffer(res.data);}
};
这篇关于腾讯tts获取文件blob推流解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!