import requests
import os

API_KEY = 'YOUR_API_KEY'
SECRET_KEY = 'YOUR_SECRET_KEY'
# 通过AK、SK获取token或通过安全认证中心获取IAM APIKEY两种鉴权方式二选一
IAM_API_KEY='YOUR_IAM_API_KEY'

def baidu_voice_clone_tts():

    token = get_access_token()
    # API接口地址
    if "bce-v3" in IAM_API_KEY:
        url = "https://aip.baidubce.com/rest/2.0/speech/publiccloudspeech/v1/voice/clone/tts"
    else:
        url = f"https://aip.baidubce.com/rest/2.0/speech/publiccloudspeech/v1/voice/clone/tts?access_token={token}"

    # 请求头
    headers = {
        "Content-Type": "application/json",
        "Authorization": 'Bearer ' + IAM_API_KEY
    }

    # 请求体参数
    payload = {
        "voice_id": 123,
        "text": "欢迎使用百度语音合成",
        "dialect":"wuu-CN-shanghai",  # 方言控制参数
        "emotion": "happy",  # 情绪控制参数
        "media_type": "wav",
        "sample_rate": 24000,  # 采样率控制参数
        "pitch": 5,
        "volume": 5,
        "speed": 5
    }

    # 发送POST请求
    response = requests.post(url, headers=headers, json=payload, timeout=30)

    # 处理响应
    if 'audio/' in response.headers.get('content-type', ''):
        file_name = f"result.wav"
        with open(file_name, 'wb') as f:
            f.write(response.content)
        print(f"音频生成成功，已保存为{file_name}")
    else:
        response.encoding = "utf-8"
        print("请求失败，错误信息：", response.text)

def get_access_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {
        "grant_type": "client_credentials",
        "client_id": API_KEY,
        "client_secret": SECRET_KEY
    }
    response = requests.post(url, params=params)
    token_data = response.json()
    return token_data.get("access_token")

if __name__ == "__main__":
    # 运行前请先安装依赖：pip install requests
    baidu_voice_clone_tts()