Local-Voice/test_audio_recording.py
2025-09-18 21:21:34 +08:00

187 lines
5.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""
音频录音测试脚本
用于测试树莓派的音频录音功能
"""
import subprocess
import time
import sys
import os
import signal
def test_audio_recording():
"""测试音频录音功能"""
print("=== 音频录音测试 ===")
# 检查录音设备
print("\n1. 检查录音设备...")
try:
result = subprocess.run(['arecord', '-l'], capture_output=True, text=True)
if result.returncode == 0:
print("录音设备列表:")
print(result.stdout)
else:
print("错误: 无法获取录音设备列表")
return False
except FileNotFoundError:
print("错误: arecord 命令未找到,请安装 alsa-utils")
return False
# 录制测试音频
print("\n2. 录制测试音频5秒...")
test_record_file = "/tmp/test_record.wav"
try:
print("请对着麦克风说话5秒录音开始...")
# 录制5秒音频
result = subprocess.run(['arecord', '-d', '5', '-f', 'cd', test_record_file],
capture_output=True, text=True)
if result.returncode == 0:
print("✓ 音频录制成功")
# 检查文件是否存在且大小合理
if os.path.exists(test_record_file):
file_size = os.path.getsize(test_record_file)
print(f"录制文件大小: {file_size} 字节")
if file_size > 1000: # 至少1KB
print("✓ 录音文件大小正常")
return True
else:
print("✗ 录音文件太小,可能录音失败")
return False
else:
print("✗ 录音文件未创建")
return False
else:
print("✗ 音频录制失败")
print(f"错误信息: {result.stderr}")
return False
except FileNotFoundError:
print("错误: arecord 命令未找到")
return False
except KeyboardInterrupt:
print("\n录音被用户中断")
return False
def test_audio_playback_verification():
"""播放录制的音频进行验证"""
print("\n3. 播放录制的音频进行验证...")
test_record_file = "/tmp/test_record.wav"
if not os.path.exists(test_record_file):
print("错误: 找不到录制的音频文件")
return False
try:
print("播放录制的音频...")
result = subprocess.run(['aplay', test_record_file], capture_output=True, text=True)
if result.returncode == 0:
print("✓ 录音播放成功")
return True
else:
print("✗ 录音播放失败")
print(f"错误信息: {result.stderr}")
return False
except FileNotFoundError:
print("错误: aplay 命令未找到")
return False
def test_microphone_levels():
"""测试麦克风音量级别"""
print("\n4. 测试麦克风音量级别...")
try:
# 获取麦克风音量
result = subprocess.run(['amixer', 'sget', 'Capture'], capture_output=True, text=True)
if result.returncode == 0:
print("当前麦克风音量:")
print(result.stdout)
# 设置麦克风音量
subprocess.run(['amixer', 'sset', 'Capture', '80%'], check=True)
print("✓ 麦克风音量已设置为80%")
return True
else:
print("无法获取麦克风音量信息")
return False
except (subprocess.CalledProcessError, FileNotFoundError):
print("amixer 命令未找到或执行失败")
return False
def test_realtime_monitoring():
"""实时音频监控测试"""
print("\n5. 实时音频监控测试3秒...")
try:
print("开始实时监控,请对着麦克风说话...")
# 使用parecord进行实时监控如果可用
cmd = ['parecord', '--monitor', '--latency-msec', '100', '--duration', '3', '/dev/null']
result = subprocess.run(cmd, capture_output=True, text=True, timeout=5)
if result.returncode == 0:
print("✓ 实时监控测试成功")
return True
else:
print("提示: 实时监控测试跳过需要pulseaudio")
return True
except (subprocess.TimeoutExpired, FileNotFoundError, subprocess.CalledProcessError):
print("提示: 实时监控测试跳过")
return True
def cleanup():
"""清理测试文件"""
test_files = ["/tmp/test_record.wav"]
for file_path in test_files:
if os.path.exists(file_path):
try:
os.remove(file_path)
print(f"✓ 已清理测试文件: {file_path}")
except OSError:
print(f"警告: 无法清理测试文件: {file_path}")
if __name__ == "__main__":
print("树莓派音频录音功能测试")
print("=" * 40)
success = True
# 测试麦克风音量
if not test_microphone_levels():
success = False
# 测试音频录制
if not test_audio_recording():
success = False
# 播放录制的音频
if os.path.exists("/tmp/test_record.wav"):
if not test_audio_playback_verification():
success = False
# 实时监控测试
if not test_realtime_monitoring():
success = False
print("\n" + "=" * 40)
if success:
print("✓ 所有音频录音测试通过")
else:
print("✗ 部分音频录音测试失败")
# 清理测试文件
cleanup()
sys.exit(0 if success else 1)