有道云语音合成

文档

代码

import os
import random

from time import sleep

import requests
import docx
from utils.AuthV3Util import addAuthParams

# 您的应用ID
APP_KEY = '2ea9d5aecfc'
# 您的应用密钥
APP_SECRET = 'e0TqlHxT4sD5cZxQERTwgD'

# 合成音频保存路径, 例windows路径:PATH = "C:\\tts\\media.mp3"
PATH = 'C:\\Users\\23274\\Desktop\\new1\\'
files=[]


def read_file_2list(file):
    file1=docx.Document(file)
    Str = ''
    for para in file1.paragraphs:
        Str+=para.text
    #判断文档是英文还是中文,英文分割.结尾不超过1000。中文。分割不超过330
    list=[]
    sp={
    
    "en": ".","zh": "。"}
    lang={
    
    "en": 500,"zh": 330}
            #index = random.randrange(len(Str))  # 随机生成一个下标
    if len(Str[random.randint(0,len(Str))].encode('utf-8'))==1 and len(Str[random.randint(0,len(Str))].encode('utf-8'))==1:
        doclanguge='en'
    else:
        doclanguge='zh'
    if len(Str)<lang[doclanguge]:  #不用分割
        return [Str]
    #分割
    sentences_2=Str
    while(len(sentences_2)> lang[doclanguge] ):
        sentences_1 = sentences_2[:lang[doclanguge]]
        locate=sentences_1.rfind(sp[doclanguge])   #找到最大长度的。截断
        if locate==-1:
            locate=lang[doclanguge]
        list.append(sentences_1[0:locate+1])
        print(len(sentences_1[0:locate+1]),sentences_1[0:locate+1])
        sentences_2=sentences_2[locate+1:]

    list.append(sentences_2)
    return list


def createRequest(item,q_i,voice,speed):
    q=q_i
    voiceName = voice
    format = 'mp3'
    speed=speed
    data = {
    
    'q': q, 'voiceName': voiceName, "speed" : speed,'format': format}

    addAuthParams(APP_KEY, APP_SECRET, data)

    header = {
    
    'Content-Type': 'application/x-www-form-urlencoded'}
    res = doCall('https://openapi.youdao.com/ttsapi', header, data, 'post')
    saveFile(res,item,voice,speed)


def doCall(url, header, params, method):
    if 'get' == method:
        return requests.get(url, params)
    elif 'post' == method:
        return requests.post(url, params, header)


def saveFile(res,item,voice,speed):
    contentType = res.headers['Content-Type']
    isExists = os.path.exists(PATH)
    if not isExists:
        os.makedirs(PATH)
    path=PATH+str(item)+"_"+voice+str(speed)+'.mp3'
    files.append(path)
    if 'audio' in contentType:
        fo = open(path, 'wb+')
        fo.write(res.content)
        fo.close()
        print('save file path: ' + path)
    else:
        print(str(res.content, 'utf-8'))

# 网易有道智云语音合成服务api调用demo
# api接口: https://openapi.youdao.com/ttsapi
def combine_mp3(files,name):
    path='C:\\Users\\23274\\Desktop\\英语演讲\\'+name+'.mp3'
    with open(path,'ab') as f:
        for i in files:
            with open(i,'rb') as f1:
                f.write(f1.read())
    return

if __name__ == '__main__':
    list=read_file_2list("C:\\Users\\23274\\Desktop\\最终版.docx")
    #list=read_file_2list("C:\\Users\\23274\\Documents\\WeChat Files\\wxid_rw04djusmvta22\\FileStorage\\File\\2023-06\\6.3.docx")
    for i,doc in enumerate(list):
       createRequest(i,doc,'youyingying',1)
    print(files)

    combine_mp3(files)

    # name=['youxiaozhi','youxiaoxun',"youxiaoqin",'youxiaofu','youyuting','youtingting','youxiaohao','youxiaonan','youxiaomei',
    #       'youxiaoying','youkejiang','gongqishuai','youxiaobei','weixiaomei','weixiaoying','youmeimei','youyingying',
    #       'piaozhiyou','anna','youxiaoyue','aimina','axiya','weijiatai','weixiaojia','Alois','bara','Molly','William','Olivia'
    #       ,'neale','Osric','Rama','Noah','fenxiaomei','fenxiaoshuai','faxiaomei','faxiaoshuai','fadana','dexiaomei',
    #       'dexiaoshuai','xixiaoshuai','xiboxiaoshuai','yindixiaoshuai','yindixiaomei','xiongxiaoshuai','yixiaoshuai','yixiaomei']
    # for i,name in enumerate(name):
    #     sleep(1.5)
    #     createRequest(i, '我', name, 1)

猜你喜欢

转载自blog.csdn.net/weixin_44932880/article/details/131296873