import requests import json import base64 import io import sounddevice as sd import soundfile as sf # API 地址 url = "http://127.0.0.1:8000/synthesize" # 请求体 payload = {"text": "Hello, world!"} # 请求头 headers = {"Content-Type": "application/json"} # 发送 POST 请求 try: print("Sending request to the API...") response = requests.post(url, data=json.dumps(payload), headers=headers) response.raise_for_status() # 检查请求是否成功 result = response.json() print("Response received.") # 检查返回的音频数据 if "audio" in result: print("Audio data received as Base64.") # 解码 Base64 音频数据 audio_base64 = result["audio"] audio_bytes = base64.b64decode(audio_base64) # 使用 soundfile 直接从内存中读取音频数据 try: audio_data, samplerate = sf.read(io.BytesIO(audio_bytes)) print(f"Playing audio (sample rate: {samplerate} Hz)...") sd.play(audio_data, samplerate) sd.wait() # 等待播放完成 print("Audio playback finished.") except sf.LibsndfileError as e: print(f"Error reading audio data: {e}") else: print("Unexpected response format. No audio data found.") except requests.exceptions.RequestException as e: print(f"Request failed: {e}") except Exception as e: print(f"An error occurred: {e}")