server_recording_api_async_backup.py
22.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AIfeng/2025-07-01 16:51:01
服务端录音Web API接口 - aiohttp版本
提供HTTP和WebSocket接口控制服务端录音功能
"""
import asyncio
import json
import time
from typing import Dict, Any, Optional
from aiohttp import web, WSMsgType
import aiohttp_cors
import threading
import weakref
import util
from server_audio_recorder import ServerAudioRecorder, get_global_recorder, create_global_recorder, destroy_global_recorder, PYAUDIO_AVAILABLE
from funasr_asr import FunASRClient
import config_util as cfg
from logger import logger
class ServerRecordingAPI:
"""服务端录音API管理器 - aiohttp版本"""
def __init__(self):
self.recorder = None
self.asr_client = None
self.websocket_clients = weakref.WeakSet()
logger.info("服务端录音API初始化完成")
def register_routes(self, app: web.Application):
"""注册API路由到aiohttp应用"""
# HTTP API路由
app.router.add_get('/api/server-recording/status', self.get_recording_status)
app.router.add_get('/api/server-recording/devices', self.list_audio_devices)
app.router.add_post('/api/server-recording/start', self.start_recording)
app.router.add_post('/api/server-recording/stop', self.stop_recording)
app.router.add_get('/api/server-recording/config', self.get_recording_config)
app.router.add_post('/api/server-recording/config', self.set_recording_config)
# WebSocket路由
app.router.add_get('/ws/server-recording', self.recording_websocket)
# 测试页面
app.router.add_get('/server-recording-test', self.test_page)
logger.info("服务端录音API路由注册完成")
async def get_recording_status(self, request):
"""获取录音状态"""
try:
if not PYAUDIO_AVAILABLE:
return web.json_response({
'success': False,
'error': 'pyaudio未安装,服务端录音功能不可用',
'pyaudio_available': False
})
recorder = get_global_recorder()
if recorder:
status = recorder.get_status()
status['success'] = True
return web.json_response(status)
else:
return web.json_response({
'success': True,
'is_recording': False,
'pyaudio_available': True,
'recorder_created': False
})
except Exception as e:
logger.error(f"获取录音状态失败: {e}")
return web.json_response({
'success': False,
'error': str(e)
})
async def list_audio_devices(self, request):
"""列出音频设备"""
try:
if not PYAUDIO_AVAILABLE:
return web.json_response({
'success': False,
'error': 'pyaudio未安装',
'devices': []
})
recorder = ServerAudioRecorder()
devices = recorder.list_audio_devices()
return web.json_response({
'success': True,
'devices': devices
})
except Exception as e:
logger.error(f"列出音频设备失败: {e}")
return web.json_response({
'success': False,
'error': str(e),
'devices': []
})
async def start_recording(self, request):
"""开始服务端录音"""
try:
if not PYAUDIO_AVAILABLE:
return web.json_response({
'success': False,
'error': 'pyaudio未安装,无法启动服务端录音'
})
# 获取参数
try:
data = await request.json()
except:
data = {}
sample_rate = data.get('sample_rate', 16000)
channels = data.get('channels', 1)
chunk_size = data.get('chunk_size', 1024)
device_index = data.get('device_index')
# 创建录音器
recorder = create_global_recorder(
sample_rate=sample_rate,
channels=channels,
chunk_size=chunk_size,
device_index=device_index
)
# 设置回调
recorder.set_callbacks(
on_speech_start=self._on_speech_start,
on_speech_end=self._on_speech_end,
on_audio_data=self._on_audio_data,
on_recognition_result=self._on_recognition_result
)
# 创建ASR客户端
class MockOpt:
def __init__(self):
self.fps = 50
self.batch_size = 1
self.l = 10
self.r = 10
self.username = data.get('username', 'server_user')
asr_client = FunASRClient(MockOpt())
recorder.connect_asr(asr_client)
# 开始录音
if recorder.start_recording():
self.recorder = recorder
self.asr_client = asr_client
return web.json_response({
'success': True,
'message': '服务端录音已开始',
'config': {
'sample_rate': sample_rate,
'channels': channels,
'chunk_size': chunk_size,
'device_index': device_index
}
})
else:
return web.json_response({
'success': False,
'error': '启动录音失败'
})
except Exception as e:
logger.error(f"启动服务端录音失败: {e}")
return web.json_response({
'success': False,
'error': str(e)
})
async def stop_recording(self, request):
"""停止服务端录音"""
try:
recorder = get_global_recorder()
if recorder:
recorder.stop_recording()
destroy_global_recorder()
self.recorder = None
self.asr_client = None
return web.json_response({
'success': True,
'message': '服务端录音已停止'
})
else:
return web.json_response({
'success': True,
'message': '录音器未运行'
})
except Exception as e:
logger.error(f"停止服务端录音失败: {e}")
return web.json_response({
'success': False,
'error': str(e)
})
async def get_recording_config(self, request):
"""获取录音配置"""
return web.json_response({
'success': True,
'config': {
'sample_rate': 16000,
'channels': 1,
'chunk_size': 1024,
'vad_threshold': 0.01,
'silence_duration': 1.0,
'speech_duration': 0.3,
'asr_server': f"{cfg.local_asr_ip}:{cfg.local_asr_port}"
}
})
async def set_recording_config(self, request):
"""设置录音配置"""
try:
data = await request.json()
# 这里可以保存配置到文件
return web.json_response({
'success': True,
'message': '配置已更新'
})
except Exception as e:
return web.json_response({
'success': False,
'error': str(e)
})
async def recording_websocket(self, request):
"""录音WebSocket接口"""
ws = web.WebSocketResponse()
await ws.prepare(request)
self.websocket_clients.add(ws)
logger.info(f"WebSocket客户端已连接,当前连接数: {len(self.websocket_clients)}")
try:
async for msg in ws:
if msg.type == WSMsgType.TEXT:
try:
data = json.loads(msg.data)
await self._handle_websocket_message(ws, data)
except json.JSONDecodeError:
await ws.send_str(json.dumps({
'type': 'error',
'message': '无效的JSON格式'
}))
elif msg.type == WSMsgType.ERROR:
logger.error(f"WebSocket错误: {ws.exception()}")
break
except Exception as e:
logger.error(f"WebSocket连接异常: {e}")
finally:
self.websocket_clients.discard(ws)
logger.info(f"WebSocket客户端已断开,当前连接数: {len(self.websocket_clients)}")
return ws
async def test_page(self, request):
"""测试页面"""
html_content = '''
<!DOCTYPE html>
<html>
<head>
<title>服务端录音测试</title>
<meta charset="utf-8">
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.button { padding: 10px 20px; margin: 5px; background: #007cba; color: white; border: none; border-radius: 4px; cursor: pointer; }
.button:hover { background: #005a87; }
.button:disabled { background: #ccc; cursor: not-allowed; }
#output { margin-top: 20px; padding: 10px; background: #f5f5f5; border-radius: 4px; max-height: 400px; overflow-y: auto; }
.status { padding: 10px; margin: 10px 0; border-radius: 4px; }
.status.success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
.status.error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
.status.info { background: #d1ecf1; color: #0c5460; border: 1px solid #bee5eb; }
</style>
</head>
<body>
<h1>🎤 服务端录音API测试</h1>
<div>
<button class="button" onclick="getStatus()">📊 获取状态</button>
<button class="button" onclick="listDevices()">🎧 列出设备</button>
<button class="button" onclick="startRecording()" id="startBtn">▶️ 开始录音</button>
<button class="button" onclick="stopRecording()" id="stopBtn" disabled>⏹️ 停止录音</button>
<button class="button" onclick="connectWebSocket()">🔌 连接WebSocket</button>
<button class="button" onclick="clearOutput()">🗑️ 清空日志</button>
</div>
<div id="output"></div>
<script>
let ws = null;
function log(message, type = 'info') {
const output = document.getElementById('output');
const timestamp = new Date().toLocaleTimeString();
const div = document.createElement('div');
div.className = `status ${type}`;
div.innerHTML = `[${timestamp}] ${message}`;
output.appendChild(div);
output.scrollTop = output.scrollHeight;
}
function clearOutput() {
document.getElementById('output').innerHTML = '';
}
async function getStatus() {
try {
const response = await fetch('/api/server-recording/status');
const data = await response.json();
log('状态: ' + JSON.stringify(data, null, 2), data.success ? 'success' : 'error');
// 更新按钮状态
if (data.success && data.is_recording) {
document.getElementById('startBtn').disabled = true;
document.getElementById('stopBtn').disabled = false;
} else {
document.getElementById('startBtn').disabled = false;
document.getElementById('stopBtn').disabled = true;
}
} catch (e) {
log('错误: ' + e.message, 'error');
}
}
async function listDevices() {
try {
const response = await fetch('/api/server-recording/devices');
const data = await response.json();
log('设备列表: ' + JSON.stringify(data, null, 2), data.success ? 'success' : 'error');
} catch (e) {
log('错误: ' + e.message, 'error');
}
}
async function startRecording() {
try {
const response = await fetch('/api/server-recording/start', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
sample_rate: 16000,
channels: 1,
chunk_size: 1024
})
});
const data = await response.json();
log('开始录音: ' + JSON.stringify(data, null, 2), data.success ? 'success' : 'error');
if (data.success) {
document.getElementById('startBtn').disabled = true;
document.getElementById('stopBtn').disabled = false;
}
} catch (e) {
log('错误: ' + e.message, 'error');
}
}
async function stopRecording() {
try {
const response = await fetch('/api/server-recording/stop', {
method: 'POST'
});
const data = await response.json();
log('停止录音: ' + JSON.stringify(data, null, 2), data.success ? 'success' : 'error');
document.getElementById('startBtn').disabled = false;
document.getElementById('stopBtn').disabled = true;
} catch (e) {
log('错误: ' + e.message, 'error');
}
}
function connectWebSocket() {
if (ws && ws.readyState === WebSocket.OPEN) {
log('WebSocket已连接', 'info');
return;
}
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${protocol}//${window.location.host}/ws/server-recording`;
ws = new WebSocket(wsUrl);
ws.onopen = function() {
log('WebSocket连接已建立', 'success');
};
ws.onmessage = function(event) {
try {
const data = JSON.parse(event.data);
log('WebSocket消息: ' + JSON.stringify(data, null, 2), 'info');
} catch (e) {
log('WebSocket消息: ' + event.data, 'info');
}
};
ws.onclose = function() {
log('WebSocket连接已关闭', 'error');
};
ws.onerror = function(error) {
log('WebSocket错误: ' + error, 'error');
};
}
// 页面加载时获取状态
window.onload = function() {
getStatus();
};
</script>
</body>
</html>
'''
return web.Response(text=html_content, content_type='text/html')
async def _handle_websocket_message(self, ws, data: Dict[str, Any]):
"""处理WebSocket消息"""
message_type = data.get('type')
if message_type == 'start_recording':
# 开始录音
config = data.get('config', {})
await ws.send_str(json.dumps({
'type': 'recording_started',
'timestamp': time.time()
}))
elif message_type == 'stop_recording':
# 停止录音
await ws.send_str(json.dumps({
'type': 'recording_stopped',
'timestamp': time.time()
}))
elif message_type == 'get_status':
# 获取状态
recorder = get_global_recorder()
if recorder:
status = recorder.get_status()
else:
status = {'is_recording': False}
await ws.send_str(json.dumps({
'type': 'status',
'data': status,
'timestamp': time.time()
}))
else:
await ws.send_str(json.dumps({
'type': 'error',
'message': f'未知消息类型: {message_type}'
}))
async def _broadcast_to_websockets(self, message: Dict[str, Any]):
"""广播消息到所有WebSocket客户端"""
if not self.websocket_clients:
return
message_json = json.dumps(message)
disconnected_clients = set()
for ws in list(self.websocket_clients):
try:
if not ws.closed:
await ws.send_str(message_json)
else:
disconnected_clients.add(ws)
except Exception as e:
logger.error(f"发送WebSocket消息失败: {e}")
disconnected_clients.add(ws)
# 清理断开的连接
for ws in disconnected_clients:
self.websocket_clients.discard(ws)
def _on_speech_start(self):
"""语音开始回调"""
logger.info("[MIC] 检测到语音开始")
# 使用线程安全的方式调度协程到主事件循环
try:
loop = asyncio.get_event_loop()
if loop.is_running():
asyncio.run_coroutine_threadsafe(self._broadcast_to_websockets({
'type': 'speech_start',
'timestamp': time.time()
}), loop)
except RuntimeError:
# 如果没有事件循环,忽略广播
pass
def _on_speech_end(self):
"""语音结束回调"""
logger.info("[STOP] 检测到语音结束")
# 使用线程安全的方式调度协程到主事件循环
try:
loop = asyncio.get_event_loop()
if loop.is_running():
asyncio.run_coroutine_threadsafe(self._broadcast_to_websockets({
'type': 'speech_end',
'timestamp': time.time()
}), loop)
except RuntimeError:
# 如果没有事件循环,忽略广播
pass
def _on_audio_data(self, audio_data, vad_result):
"""音频数据回调"""
# 发送音频状态到WebSocket客户端
if vad_result['is_speech']:
# 使用线程安全的方式调度协程到主事件循环
try:
loop = asyncio.get_event_loop()
if loop.is_running():
asyncio.run_coroutine_threadsafe(self._broadcast_to_websockets({
'type': 'audio_data',
'volume': vad_result['volume'],
'threshold': vad_result['threshold'],
'is_speech': True,
'timestamp': time.time()
}), loop)
except RuntimeError:
# 如果没有事件循环,忽略广播
pass
def _on_recognition_result(self, result: str):
"""识别结果回调"""
logger.info(f"🎯 识别结果: {result}")
# 使用线程安全的方式调度协程到主事件循环
try:
loop = asyncio.get_event_loop()
if loop.is_running():
asyncio.run_coroutine_threadsafe(self._broadcast_to_websockets({
'type': 'recognition_result',
'text': result,
'timestamp': time.time()
}), loop)
except RuntimeError:
# 如果没有事件循环,忽略广播
pass
# 全局API实例
server_recording_api = ServerRecordingAPI()
def register_server_recording_api(app: web.Application) -> ServerRecordingAPI:
"""注册服务端录音API到aiohttp应用"""
server_recording_api.register_routes(app)
return server_recording_api
if __name__ == "__main__":
# 测试服务器
async def init_app():
app = web.Application()
register_server_recording_api(app)
# 配置CORS
cors = aiohttp_cors.setup(app, defaults={
"*": aiohttp_cors.ResourceOptions(
allow_credentials=True,
expose_headers="*",
allow_headers="*",
)
})
for route in list(app.router.routes()):
cors.add(route)
return app
async def main():
app = await init_app()
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, '0.0.0.0', 8001)
await site.start()
print("🎤 服务端录音API测试服务器启动: http://localhost:8001/server-recording-test")
try:
await asyncio.Future() # 永远运行
except KeyboardInterrupt:
pass
finally:
await runner.cleanup()
asyncio.run(main())