Files
aistream-test/测试流式传输uniapp/uni_modules/sdx-StreamPlayer/components/sdx-StreamPlayer/sdx-StreamPlayer.vue
T
2025-12-01 21:00:54 +08:00

111 lines
3.1 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<template>
<button type="default" @click="connect">播放音频</button>
<button type="default" @click="end">结束播放</button>
<!-- 逻辑层和renderjs的交互需要通过这种方式传递数据具体看文档 -->
<view :isStop="isStop" :change:isStop="renderJS.stop" :prop="currBuffer" :change:prop="renderJS.playTTS" type="renderjs" module="renderJS"></view>
</template>
<script>
/**
* 本页面代码为仅供参考的案例,只列举了实现思路,是我从项目代码中抽出来的,具体是否能跑通需要测试
* 核心代码在plugins
*/
let ws = null
export default {
data(){
return {
currBuffer: null,
isStop: false,
isStreamPlaying: false
}
},
methods: {
connect() {
this.ws = uni.connectSocket({
url: 'ws://172.16.89.58:8000/ws/audio',
complete: () => {
console.log('complete');
},
success: () => {
console.log('web');
this.ws.onOpen((res) => {
console.log('WebSocket连接已打开', res);
this.ws.onMessage((res) => {
let messageData = res.data;
// 处理不同类型的数据
if (typeof messageData === 'string') {
// 文本数据
try {
const parsedData = JSON.parse(messageData);
this.handleMessage(parsedData);
} catch (e) {
this.handleMessage(messageData);
}
} else if (messageData instanceof ArrayBuffer) {
// 二进制数据
this.isStreamPlaying = true
this.currBuffer= uni.arrayBufferToBase64(messageData)
try {
// const str = this.arrayBufferToStringCompat(messageData);
// console.log('转换后的字符串:', str);
} catch (e) {
console.log('二进制数据解析失败:', e);
}
}
})
});
}})
},
end() {
this.isStop = !this.isStop
},
changeStreamPlaying(e) {
this.isStreamPlaying = e.type
},
appendBuffer(messageData) {
this.isStreamPlaying = true
this.currBuffer= uni.arrayBufferToBase64(messageData)
}
}
}
</script>
<script module="renderJS" lang="renderjs">
/**
* 如果不需要支持iOS,建议使用这个,同时支持mp3和pcm
*/
// import { StreamPlayer } from "../../plugins/H5AndAndroidStreamPlayer";
/**
* 如果需要支持安卓iOS和H5,使用这个,支持pcm,暂时不支持mp3
* 如果想支持mp3可以自己开发,我在测试中mp3的效果太差所以放弃了。
*/
import { StreamPlayer } from "../../plugins/StreamPlayer";
let player=null
export default {
mounted() {
const _this = this;
player = new StreamPlayer({callback: _this.callback});
},
methods: {
playTTS (base64) {
console.log('base64', base64);
if(!base64)return
const binaryStr = atob(base64)
const bytes = new Uint8Array(binaryStr.length)
for (let i = 0; i < binaryStr.length; i++) {
bytes[i] = binaryStr.charCodeAt(i)
}
player.appendChunk(bytes.buffer);
},
stop() {
player&&player.destroy()
player = null
},
callback(e) {
if(e==='ended') {
this.$ownerInstance.callMethod('changeStreamPlaying', {type: false});
}
}
}
}
</script>