test_microphone_simple.py 3.19 KB
# AIfeng/2025-07-07 10:27:00
# 简单麦克风测试脚本
# 测试修改后的音量阈值是否能正确检测语音

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from streaming.streaming_recorder import StreamingRecorder
import time

def test_microphone_detection():
    """测试麦克风语音检测"""
    print("=== 麦克风语音检测测试 ===")
    print("使用修改后的低音量阈值配置")
    print("请对着麦克风说话,观察是否能检测到语音...")
    print("测试时长: 10秒")
    print("按Ctrl+C提前结束测试")
    print()
    
    # 创建录音器实例
    recorder = StreamingRecorder(
        volume_threshold=0.005,  # 使用低阈值
        silence_duration=1.0,
        min_speech_duration=0.3,
        max_speech_duration=15.0,
        partial_result_interval=2.0,
        username="microphone_test"
    )
    
    # 设置回调函数
    speech_detected = False
    
    def on_partial_result(session_id, text, confidence):
        nonlocal speech_detected
        speech_detected = True
        print(f"✅ 检测到语音! 部分结果: {text} (置信度: {confidence:.2f})")
    
    def on_final_result(session_id, text, confidence):
        print(f"✅ 最终结果: {text} (置信度: {confidence:.2f})")
    
    def on_status_update(status):
        if status.get('type') == 'vad_status':
            volume = status.get('volume', 0)
            is_speaking = status.get('is_speaking', False)
            threshold = status.get('threshold', 0)
            
            if is_speaking:
                print(f"🎤 语音检测中 - 音量: {volume:.4f}, 阈值: {threshold:.4f}")
            elif volume > 0.001:  # 只显示有一定音量的静音状态
                print(f"🔇 静音状态 - 音量: {volume:.4f}, 阈值: {threshold:.4f}")
    
    recorder.on_partial_result = on_partial_result
    recorder.on_final_result = on_final_result
    recorder.on_status_update = on_status_update
    
    try:
        # 开始录音
        if recorder.start_recording():
            print("录音已开始,请说话...")
            
            # 等待10秒
            start_time = time.time()
            while time.time() - start_time < 10:
                time.sleep(0.1)
            
            print("\n测试结束")
            
        else:
            print("❌ 录音启动失败")
            
    except KeyboardInterrupt:
        print("\n测试被用户中断")
    
    finally:
        # 停止录音
        recorder.stop_recording()
        
        # 显示测试结果
        print("\n=== 测试结果 ===")
        if speech_detected:
            print("✅ 成功检测到语音,麦克风工作正常")
        else:
            print("❌ 未检测到语音,可能存在以下问题:")
            print("   1. 麦克风音量过低")
            print("   2. 环境噪音干扰")
            print("   3. 麦克风权限问题")
            print("   4. 音频设备配置问题")
            print("\n建议:")
            print("   - 检查系统音量设置")
            print("   - 尝试更换音频设备")
            print("   - 检查应用权限设置")

if __name__ == "__main__":
    test_microphone_detection()