| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- # 音频播放模块
- import os
- import platform
- import subprocess
- def play(audio_path: str):
- """
- 播放音频文件
- 输入:本地音频文件路径
- """
- if not os.path.exists(audio_path):
- raise FileNotFoundError(f'音频文件不存在: {audio_path}')
- system = platform.system()
- if system == 'Darwin': # macOS
- subprocess.run(['afplay', audio_path])
- elif system == 'Linux':
- # 尝试多个播放器
- for player in ['aplay', 'paplay', 'mpg123', 'ffplay']:
- try:
- subprocess.run(
- [player, audio_path],
- check=True,
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
- )
- return
- except FileNotFoundError:
- continue
- raise Exception('找不到可用的音频播放器')
- elif system == 'Windows':
- # Windows 用 PowerShell 播放
- subprocess.run(
- ['powershell', '-c', f'(New-Object Media.SoundPlayer "{audio_path}").PlaySync()'],
- shell=True,
- )
- else:
- raise Exception(f'不支持的系统: {system}')
- def play_url(audio_url: str):
- """直接播放 URL(先下载)"""
- from tts_client import download_audio
- local_path = download_audio(audio_url)
- try:
- play(local_path)
- finally:
- # 清理临时文件
- try:
- os.unlink(local_path)
- except OSError:
- pass
- if __name__ == '__main__':
- from tts_client import synthesize_and_download
- audio_path = synthesize_and_download('测试播放')
- play(audio_path)
|