首页 > 其他分享 >文字转语音

文字转语音

时间:2022-12-07 14:13:58浏览次数:41  
标签:文字 engine lan convertTable text per mp3 语音

文字转语音方法有:

1.百度TTS

可直接用浏览器访问 https://tts.baidu.com/text2audio?tex=hello world&cuid=baike&lan=ZH&ie=utf-8&ctp=1&pdt=301&vol=9&rate=32&per=0

2.python的模块pyttsx3

自己写的程序

3.找网上的录音工具录制网页的声音,比如楼月录音软件

 

import requests
import os
import easygui

def TTS(text, speed, lan, per):
    """
    :param text: 要转为语音的文本内容
    :param speed: 朗读速度,取值范围[1,9]
    :param lan: 语言码,ZH 普通话, EN 美式英语, UK 英式英语, CTE 粤语
    :param per: 音色码
    :return:
    """
    convertTable = {  # 建立易读文本和音色码/语言码的关系表
        '中文': ('ZH', {
            '标准女音': 0,
            '标准男音': 1,
            '斯文男音': 3,
            '小萌萌': 4,
            '知性女音': 5,
            '老教授': 6,
            '葛平音': 8,
            '播音员': 9,
            '京腔': 10,
            '温柔大叔': 11
        }),
        '英式英语': ('UK', {
            '标准音': 0
        }),
        '美式英语': ('EN', {
            '标准音': 0
        }),
        '粤语': ('CTE', {
            '标准音': 0
        })
    }
    print(convertTable[lan][0], convertTable[lan][1][per])
    data = {
        'tex': text,
        'spd': speed, # 语速,取值0-15,5是中语速
        'lan': convertTable[lan][0],
        'per': convertTable[lan][1][per],
        'ctp': 1,
        'cuid': 'baike',
        'ie': 'UTF-8',
        'pdt': 301,
        'vol': 9,  # 音量,取值0-9,5是中音量
        'rate': 32
    }
    result = requests.get('https://tts.baidu.com/text2audio', params=data)
    try:
        r = result.json()
        print(r)
    except:
        print(result.content)
        return result.content
    else:
        raise ValueError

def baidu_tts():
    try:
        text = 'Hello'
        bindata = TTS(text, 5, '英式英语', '标准女音')
    except:
        print('转换失败')
    else:
        with open(f'{text}.mp3', 'wb') as f:
            f.write(bindata)  # 在同级目录写入为mp3文件
        os.startfile(f'{text}.mp3')     #自动运行生成的mp3

def text2audio_ttsx3(text):
    import pyttsx3
    engine = pyttsx3.init('sapi5')
    engine.setProperty('rate', 120)
    engine.setProperty('volume', 1.0)
    voices = engine.getProperty('voices')
    # for voice in voices:
    #     print(voice)
    engine.setProperty('voice', voices[0].id)

    engine.save_to_file(text, f'{text}.mp3')
    engine.say(text)
    engine.runAndWait()
    engine.stop()


if __name__ == '__main__':
    # 百度获取的音频文件有水印
    # baidu_tts()
    text = easygui.enterbox(msg='请输入中文或英文', title='文字转语音 - PYTTS', default='欢迎光临')

    if text:
        try:
            text2audio_ttsx3(text)
            easygui.msgbox(f'【{text}.mp3】\t文件下载完成')
        except:
            easygui.msgbox(f'文件下载出错啦!!!')
    else:
        if text == None:
            pass
        else:
            easygui.msgbox(f'文字不可为空!')

 

 

 

 

 

标签:文字,engine,lan,convertTable,text,per,mp3,语音
From: https://www.cnblogs.com/xiaojiaocx/p/16962471.html

相关文章