基于百度AI的文字转语音案例

1.准备工作

百度AI申请账号,然后申请接口,将ID,key填入代码中

2.工具代码

填入id,key直接使用

from aip import AipSpeech
import os

""" 你的 APPID AK SK """
APP_ID ="自己的id"
API_KEY = "KEY"
SECRET_KEY = "KEY"

speech_client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
def generate_speech(str_or_filepath, audio_name):

    text_list = []
    if os.path.isfile(str_or_filepath):
        with open(str_or_filepath, "r", encoding="utf8") as f:
            while True:
                text_content = f.read(1024)
                if not text_content:
                    break
                text_list.append(text_content)

    elif isinstance(str_or_filepath, str):
        text_part = len(str_or_filepath) // 200 + 1
        text_list = [str_or_filepath[200 * i: 200 * (i + 1)] for i in range(text_part)]

    else:
        print("输入格式错误!")
        return

    result_audio = b""
    # 第一个是文本, 第二个是语言, 第三个是平台,第四个是声音
    for text in text_list:
        print(text)
        result = speech_client.synthesis(text, "zh", 1, {
            "vol": 5,  # 音量
            "spd": 5,  # 语速
            "pit": 9,  # 语调
            "per": 0,  # 0:女 1:男 3:逍遥 4:小萝莉
        })
        if not isinstance(result, dict):
            result_audio += result
        else:
            print(result_audio)

    with open(audio_name, 'wb+') as f:
        f.write(result_audio)

3.主体代码

from aip import AipOcr
from aip import AipSpeech
from playsound import playsound
import keyboard
from speech_convert import generate_speech
from PIL import ImageGrab #粘贴操作


#使用自己的百度账号申请接
""" 你的 APPID AK SK """
APP_ID = 'ID'
API_KEY = 'KEY'
SECRET_KEY = 'KEY'

speech_client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)

# 初始化AipFace对象
aipOcr = AipOcr(APP_ID, API_KEY, SECRET_KEY)

keyboard.wait(hotkey='ctrl+alt+a')
print('begin')

keyboard.wait(hotkey='ctrl+f1')
print('end')

#获取并保存截图内容
image=ImageGrab.grabclipboard()
image.save('screen.png')

# 读取图片
filePath = "screen.png"

def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()


# 定义参数变量
options = {
    'detect_direction': 'true',
    'language_type': 'CHN_ENG',
}

# 调用通用文字识别接口
result = aipOcr.basicGeneral(get_file_content(filePath), options)
words_result = result['words_result']
result_str = ""
for data in words_result:
    result_str += data['words']

generate_speech(result_str,'audio.mp3')
playsound('audio.mp3')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值