百度语音合成
某个同学拿去开老师玩笑,用这个搞了一段音频,后来他走的很安详。
#coding=utf-8
#百度语音合成 by blog.chutian.bid
import requests,json,sys
class baidutoaudio:
def __init__(self,appKey,appSecret,Cuid):
self.ak = appKey
self.sk = appSecret
self.cuid = Cuid
self.token = self.gettoken(appKey,appSecret)
return
def utf8(self): #UTF8环境
reload(sys)
sys.setdefaultencoding('utf-8')
def getapi(self,url):
data = requests.get(url)
return data.text
def writeauido(self,url,file): #写音频
data = requests.get(url)
f = open(file, 'w+')
f.write(data.content)
f.close()
def gettoken(self,ak,sk): #获取鉴权
data = self.getapi('https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + ak + '&client_secret=' + sk)
if(data.find('error_description') == -1):
data = json.loads(data)
return data['access_token']
else:
data = json.loads(data)
print data['error_description']
return 'ERROR'
def getsay(self,tex,spd,pit,vol,per,file): #写音频并返回链接
#tex:合成用文本 spd:语速 pit:音调 vol:音量 per:发音人选择
#0为普通女声,1为普通男生,3为情感合成-度逍遥,4为情感合成-度丫丫,默认为普通女声
url = 'http://tsn.baidu.com/text2audio'
url += '?tex='
url += str(tex)
url += '&tok='
url += self.token
url += '&cuid='
url += str(self.cuid)
url += '&ctp=1&lan=zh'
url += '&spd='
url += str(spd)
url += '&vol='
url += str(vol)
url += '&per='
url += str(per)
self.writeauido(url,file)
return url
if __name__ == '__main__':
appKey = 'You AK'#AK
appSecret = 'You SK'#SK
cuid = '1'#用户ID
say = baidutoaudio(appKey,appSecret,cuid)
say.utf8()
print say.getsay(raw_input('Say:'),5,6,12,4,'say.mp3')