调用百度翻译生成语音

目标:播放输入文字

查看百度翻译URL组成

URL: https://fanyi.baidu.com/gettts?lan=zh&text=%E5%95%8A%E5%95%8A%E5%95%8A&spd=5&source=web
    https://fanyi.baidu.com/gettts? 为URL头
    lan=zh&text=%E5%95%8A%E5%95%8A%E5%95%8A&spd=5&source=web 为请求参数

编写headers和请求参数params

headers = {
    'Cookie': '自己的cookie',
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36"
           }
params = {
    'lan': 'zh',
    'text': '{}'.format(content),
    'spd': '5',
    'source': 'web'

}

使用requests中的get方法获取返回

#url为URL头
#content为需要转语音内容
response = get(url=trans_url, params=params, headers=headers).content

保存语音文件并播放

with open('test.mp3', 'wb') as f:
    f.write(response)
    f.flush()

playsound('test.mp3')

完整代码

from requests import get
from playsound import playsound

trans_url = 'https://fanyi.baidu.com/gettts?'
content = input("输入一句话:")
# content = """
# 挫折和离别不过是生命中的点缀
# """
headers = {
    'Cookie': '自己的cookie',
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36"
           }
params = {
    'lan': 'zh',
    'text': '{}'.format(content),
    'spd': '5',
    'source': 'web'

}
response = get(url=trans_url, params=params, headers=headers).content

with open('test.mp3', 'wb') as f:
    f.write(response)
    f.flush()

playsound('test.mp3')
Edit with Markdown