feat: add_websocket_voice_recognise_route 实时音频识别websocket接口

This commit is contained in:
martsforever
2025-11-02 15:39:57 +08:00
parent 16a7558dee
commit 4cf4b494f9
2 changed files with 28 additions and 0 deletions
@@ -0,0 +1,26 @@
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(websocket: WebSocket, user_id: str = Query(..., description="用户ID")):
print("新用户连接", user_id)
# 接收连接
await websocket.accept()
try:
while True:
# 将接收得到消息发送供其他用户
pcm_data_string = await websocket.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 websocket.application_state == WebSocketState.CONNECTING:
print("关闭websocket")
await websocket.close()
print("websocket已经关闭", user_id)