File size: 1,434 Bytes
2ef7c17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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}")