# 智能音箱电脑模拟版 - 主程序 import os import sys from config import Config from recorder import record_until_silence from asr import transcribe from llm import chat from tts_client import synthesize_and_download from player import play def main(): print('=' * 60) print('🎙️ 智能音箱电脑模拟版') print('=' * 60) # 验证配置 try: Config.validate() except ValueError as e: print(f'\n❌ 配置错误:\n{e}') print('\n请先复制 .env.example 为 .env 并填入 API Key') sys.exit(1) print(f'\n✅ 配置 OK') print(f' ASR: {Config.ASR_PROVIDER}') print(f' LLM: {Config.LLM_PROVIDER} / {Config.LLM_MODEL}') print(f' TTS: {Config.TTS_BASE_URL} (voice: {Config.TTS_VOICE_NAME})') print('\n操作说明:') print(' 1. 按回车开始录音') print(' 2. 说完后自动停止') print(' 3. 系统识别 → LLM 回复 → TTS 播放') print(' 4. 输入 q 退出') print() history = [] while True: user_input = input('\n[按回车录音 / 输入 q 退出] > ').strip() if user_input.lower() == 'q': print('👋 再见!') break try: # 1. 录音 print('\n[1/4] 录音...') audio_data = record_until_silence( max_seconds=Config.MAX_RECORD_SECONDS, silence_threshold=Config.SILENCE_THRESHOLD, silence_duration_ms=Config.SILENCE_DURATION_MS, ) if not audio_data: print('⚠️ 没录到声音,重试') continue # 2. ASR print('\n[2/4] 语音识别...') user_text = transcribe(audio_data) if not user_text: print('⚠️ 没识别到文字,重试') continue # 3. LLM print('\n[3/4] LLM 对话...') reply_text = chat(user_text, history) # 4. TTS(调你的 API)⭐ print('\n[4/4] TTS 合成 + 播放...') audio_path = synthesize_and_download(reply_text) play(audio_path) # 清理临时文件 try: os.unlink(audio_path) except OSError: pass # 保存历史 history.append({'role': 'user', 'content': user_text}) history.append({'role': 'assistant', 'content': reply_text}) # 只保留最近 5 轮 if len(history) > 10: history = history[-10:] except KeyboardInterrupt: print('\n\n⏸️ 中断') continue except Exception as e: print(f'\n❌ 出错了: {e}') import traceback traceback.print_exc() continue if __name__ == '__main__': main()