Files
ai-admin-server/app/controller/add_websocket_voice_recognise_route.py
T

27 lines
941 B
Python

import json
from fastapi import FastAPI, WebSocket, Query
from starlette.websockets import WebSocketState
def add_websocket_voice_recognise_route(app: FastAPI):
@app.websocket("/ws_voice_recognise")
async def ws_voice_recognise(receive_socket: WebSocket, user_id: str = Query(..., description="用户ID")):
print("新用户连接", user_id)
# 接收连接
await receive_socket.accept()
try:
while True:
# 将接收得到消息发送供其他用户
pcm_data_string = await receive_socket.receive_text()
pcm_data = json.loads(pcm_data_string)
print("pcm_data", pcm_data)
# await person_socket.send_text(data)
except Exception as e:
print(f"WebSocket error: {e}")
finally:
if receive_socket.application_state == WebSocketState.CONNECTING:
print("关闭websocket")
await receive_socket.close()
print("websocket已经关闭", user_id)