开发ai聊天页面

This commit is contained in:
田岩
2025-12-05 17:37:46 +08:00
parent 30386e6b40
commit 21b3646820
13 changed files with 1511 additions and 256 deletions
+118
View File
@@ -0,0 +1,118 @@
import {
getToken
} from '@/common/common'
import {
get_base_url
} from '@/api/request.js'
import {
ref,
onUnmounted,
computed,
getCurrentInstance
} from 'vue';
import {
ProtocolCodec,
MessageType,
SerializationType,
CompressionType,
ControlCommand,
ProtocolConst
} from './ProtocolCodec';
const DEFAULT_AUTH_PARAMS = {
user_id: '1001', // 默认用户ID(可从缓存/全局状态取)
token: '', // 优先从缓存获取,避免硬编码
name: '测试用户',
device_id: uni.getSystemInfoSync().deviceId || '', // 设备ID(补充)
timestamp: Date.now() // 时间戳(防篡改)
};
// const wsUrl = 'ws://127.0.0.1:8000/ws/audio'
const url = '/trapractice/voiceCallSocket/voiceCall'
const _baseUrl = get_base_url(url).split('http').join('ws')
export default function useWebSocket(aaas = null, options = {}) {
const isRecording = ref(false) //是否接通
const ws = ref(null)
const initConnection = (authParams = {}, onStartRecord, sssssss) => {
const wsUrl = _baseUrl + url + '?summary=' + getToken()
console.log('wsUrl', wsUrl);
const finalAuthParams = {
...DEFAULT_AUTH_PARAMS,
...authParams,
};
ws.value = uni.connectSocket({
url: wsUrl,
fail: () => {
console.log('fail');
},
success: () => {
console.log('web');
},
fail: () => {
console.log('fail');
}
});
ws.value.onOpen((res) => {
ws.value.send({
data: ProtocolCodec.pack(MessageType.IDENTITY, finalAuthParams)
});
});
ws.value.onMessage((res) => {
const {
msgType,
body
} = ProtocolCodec.unpack(res.data);
switch (msgType) {
case MessageType.IDENTITY:
console.log('身份校验', body);
onStartRecord(body)
break;
case MessageType.AUDIO_DATA:
const buffer = body;
if (buffer.byteLength < 2) break;
const uint8 = new Uint8Array(buffer);
const numArray = Array.from(uint8);
// currentPCMChunk.value = numArray;
sssssss(numArray)
// console.log('音频消息', body);
break;
case MessageType.ERROR:
// this.handleErrorMessage(body);
break;
default:
console.log('其他消息', body);
break;
}
});
}
const send = (data) => {
ws.value.send({
data
});
}
const close = () => {
ws.value.close({
code: 1000,
reason: '用户挂断',
success: () => {
console.log('挂断success');
},
fail: () => {
console.log('挂断fail');
},
complete: () => {
console.log('挂断complete');
}
});
}
return {
ws,
close,
initConnection,
send,
isRecording
};
}