import requests

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

def main():

    # 获取token
    token = get_access_token()

    # 构造POST请求的参数
    payload = {
        'tok': token,
        'tex': "欢迎使用百度语音合成",
        'per': 4196,  # 音色
        'spd': 5,  # 语速
        'pit': 5,  # 音调
        'vol': 5,  # 音量
        'aue': 3,  # 音频格式：3=mp3，4=16kpcm，5=8kpcm，6=wav
        'cuid': "Ya2hTRZEmiXLmO5NkGCg3JeR8urOY2ku",
        'lan': 'zh',
        'ctp': 1,
        'audio_ctrl': '{"AIGC": {"ContentPropagator":"XXX","PropagateID":"XXX"},"sampling_rate":16000}',
        # 注入水印参数和采样率控制参数
        'text_ctrl': '{"emo":"neutral"}'  # 音频情感
    }

    # 请求头
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': '*/*',
        'Authorization': 'Bearer ' + IAM_API_KEY
    }

    # POST请求（保留原传输方式）
    url = "https://tsn.baidu.com/text2audio"
    response = requests.post(url, headers=headers, data=payload)


    # 处理响应
    if 'audio/' in response.headers.get('content-type', ''):
        file_name = f"result.mp3"
        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__':
    main()