test_recording_cache.py
5.82 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AIfeng/2025-01-02 10:27:06
录音缓存文件测试脚本
用于验证录音过程中的文件保存和识别流程
"""
import os
import sys
import time
import tempfile
import wave
from datetime import datetime
# 添加项目根目录到路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from utils import util
from recorder_sync import RecorderSync
class TestRecorder(RecorderSync):
"""测试录音器"""
def on_speaking(self, text):
"""语音识别结果回调"""
print(f"\n🎯 识别结果: {text}")
print(f"⏰ 时间: {datetime.now().strftime('%H:%M:%S')}")
# 记录识别结果到文件
with open('recognition_results.log', 'a', encoding='utf-8') as f:
f.write(f"{datetime.now().isoformat()} - {text}\n")
def test_cache_directory():
"""测试缓存目录"""
print("=== 缓存目录测试 ===")
cache_dir = "cache_data"
print(f"缓存目录: {os.path.abspath(cache_dir)}")
print(f"目录存在: {os.path.exists(cache_dir)}")
if not os.path.exists(cache_dir):
os.makedirs(cache_dir, exist_ok=True)
print("已创建缓存目录")
# 列出目录内容
if os.path.exists(cache_dir):
files = os.listdir(cache_dir)
print(f"目录内容: {files if files else '空目录'}")
# 显示文件详情
for file in files:
file_path = os.path.join(cache_dir, file)
if os.path.isfile(file_path):
stat = os.stat(file_path)
print(f" 文件: {file}")
print(f" 大小: {stat.st_size} bytes")
print(f" 修改时间: {datetime.fromtimestamp(stat.st_mtime)}")
print()
def test_audio_file_creation():
"""测试音频文件创建"""
print("=== 音频文件创建测试 ===")
# 创建测试音频数据
sample_rate = 16000
duration = 2 # 2秒
samples = sample_rate * duration
# 生成简单的正弦波测试音频
import math
audio_data = []
for i in range(samples):
value = int(32767 * 0.3 * math.sin(2 * math.pi * 440 * i / sample_rate)) # 440Hz音调
audio_data.extend([value & 0xff, (value >> 8) & 0xff]) # 16位小端格式
audio_bytes = bytes(audio_data)
# 使用RecorderSync的save_buffer_to_file方法
class TestFay:
def on_interact(self, interact):
pass
test_fay = TestFay()
recorder = TestRecorder(test_fay)
try:
file_path = recorder.save_buffer_to_file(audio_bytes)
print(f"测试音频文件已创建: {file_path}")
if os.path.exists(file_path):
stat = os.stat(file_path)
print(f"文件大小: {stat.st_size} bytes")
print(f"创建时间: {datetime.fromtimestamp(stat.st_ctime)}")
# 验证WAV文件格式
try:
with wave.open(file_path, 'rb') as wf:
print(f"WAV格式验证:")
print(f" 声道数: {wf.getnchannels()}")
print(f" 采样宽度: {wf.getsampwidth()} bytes")
print(f" 采样率: {wf.getframerate()} Hz")
print(f" 帧数: {wf.getnframes()}")
print(f" 时长: {wf.getnframes() / wf.getframerate():.2f} 秒")
except Exception as e:
print(f"WAV文件验证失败: {e}")
else:
print("❌ 文件创建失败")
except Exception as e:
print(f"❌ 测试音频文件创建失败: {e}")
print()
def monitor_cache_directory(duration=30):
"""监控缓存目录变化"""
print(f"=== 监控缓存目录变化 ({duration}秒) ===")
cache_dir = "cache_data"
if not os.path.exists(cache_dir):
os.makedirs(cache_dir, exist_ok=True)
print(f"监控目录: {os.path.abspath(cache_dir)}")
print("开始监控...")
start_time = time.time()
last_files = set()
while time.time() - start_time < duration:
try:
current_files = set(os.listdir(cache_dir)) if os.path.exists(cache_dir) else set()
# 检查新增文件
new_files = current_files - last_files
if new_files:
for file in new_files:
file_path = os.path.join(cache_dir, file)
if os.path.isfile(file_path):
stat = os.stat(file_path)
print(f"📁 新文件: {file} ({stat.st_size} bytes)")
# 检查删除的文件
deleted_files = last_files - current_files
if deleted_files:
for file in deleted_files:
print(f"🗑️ 文件删除: {file}")
last_files = current_files
time.sleep(1)
except Exception as e:
print(f"监控出错: {e}")
time.sleep(1)
print("监控结束")
print()
def main():
"""主函数"""
print("录音缓存文件测试")
print("=" * 50)
print(f"当前工作目录: {os.getcwd()}")
print(f"测试时间: {datetime.now()}")
print()
# 1. 测试缓存目录
test_cache_directory()
# 2. 测试音频文件创建
test_audio_file_creation()
# 3. 再次检查缓存目录
test_cache_directory()
# 4. 监控缓存目录变化
print("提示: 现在可以启动录音测试,观察文件变化")
print("建议: 在另一个终端运行 'python server_recording_api_sync.py' 启动录音服务")
print()
try:
monitor_cache_directory(60) # 监控60秒
except KeyboardInterrupt:
print("\n用户中断监控")
print("测试完成")
if __name__ == "__main__":
main()