python结合腾讯语音合成生成mp3文件

我的未来我决定 提交于 2020-02-04 12:12:14

直接上代码
输入一段文字,选择对应的主播,合成语音,目前来看声音效果算是比较好的,比我用过的京东、百度语音合成要好些,1万字-2毛钱,比较ok

from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException 
from tencentcloud.tts.v20190823 import tts_client, models
import base64
import json
import os,time
import uuid
import re

yuyin = '''
0-云小宁,亲和女声(默认)
1-云小奇,亲和男声
2-云小晚,成熟男声
4-云小叶,温暖女声
5-云小欣,情感女声
6-云小龙,情感男声
1000-智侠、情感男声(新)
1001-智瑜,情感女声(新)
1002-智聆,通用女声(新)
1003-智美,客服女声(新)
1050-WeJack,英文男声(新)
1051-WeRose,英文女声(新)
'''

file_name = 'C:/Users/Administrator/Desktop/腾讯语音合成-1.mp3'

def tencent_cloud_com(file_name):
    try: 
        cred = credential.Credential("你的cdkey", "你的秘钥") 
        httpProfile = HttpProfile()
        httpProfile.endpoint = "tts.tencentcloudapi.com"
        voicetype = input(yuyin+"请输入选择语音类型数字,默认为0:") #播音声音类型
        voicetext = input("请输入您想合成的文字,小于100字:")
        if voicetype == '':
            print('你选择的声音类型是空,默认将设置为0')
            voicetype = '0'
        else:
            print('你选的声音类型是:',voicetype) 

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = tts_client.TtsClient(cred, "ap-beijing", clientProfile) 
        uuid_str = uuid.uuid1()
        print(uuid_str)

        req = models.TextToVoiceRequest()
        params = '{"Text":"'+voicetext+'","SessionId":"'+str(uuid_str)+'","ModelType":1,"VoiceType":'+voicetype+'}'
        req.from_json_string(params)

        resp = client.TextToVoice(req) 
        jsonres = resp.to_json_string()
        print(type(resp.to_json_string())) 
        
        strss=json.loads(jsonres)
        voice_base64 = strss['Audio']
#        file_name = 'C:/Users/Administrator/Desktop/腾讯语音合成-1.mp3'
        print('保存路径为:',file_name)
        resultdata=base64.b64decode(voice_base64)  #转换成base64编码
        file = open(file_name,"wb")#保存为mp3文件
        file.write(resultdata)
        file.close()

    except TencentCloudSDKException as err: 
        print(err) 

def main():
    print('开始转换(*^▽^*)')
    tencent_cloud_com(file_name)
    print('完成转换Thanks♪(・ω・)ノ')

if __name__ == '__main__':
    main()

最后会生成在桌面的语音合成文件

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!