27 lines
916 B
Python
27 lines
916 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(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)
|