win10环境中,Python实现播报一段文字(可选择男女生)

依赖库

pip install pyttsx3

示例代码

import pyttsx3


def speak(text, voice_type='male', language="cn"):
    # 初始化了 TTS 引擎
    engine = pyttsx3.init()

    # 获取当前系统中所有可用的声音
    voices = engine.getProperty('voices')

    # 选择声音
    if voice_type == 'female':
        engine.setProperty('voice', voices[1].id)
    else:
        engine.setProperty('voice', voices[0].id)

    # 播放中文(需要带CN的语音包)
    if language == "cn":
        for vType in voices:
            # print(vType)
            if "TTS_MS_ZH-CN" in vType.id:
                engine.setProperty('voice', vType.id)
                print("setup cn-voices")
                break

    # 设置语速(可选)
    rate = engine.getProperty('rate')
    engine.setProperty('rate', rate - 50)  # 适当调整语速

    # 朗读文本
    engine.say(text)
    engine.runAndWait()

# 示例使用
text_to_speak = "这几天心里颇不宁静。今晚在院子里坐着乘凉,忽然想起日日走过的荷塘,在这满月的光里,总该另有一番样子吧。月亮渐渐地升高了," \
                "墙外马路上孩子们的欢笑,已经听不见了;妻在屋里拍着闰儿,迷迷糊糊地哼着眠歌。我悄悄地披了大衫,带上门出去。"

text_to_speak = "In 1989 an 8.2 earthquake almost flattened America, killing over 30,000 people in less than " \
                "four minutes. In the midst of utter devastation and chaos, a father left his wife safely at home and " \
                "rushed to the school where his son was supposed to be, only to discover that the building was as flat as a pancake."

# print("len=",len(text_to_speak))
# for i in range(len(text_to_speak)):
#     print(text_to_speak[i])

speak(text_to_speak, voice_type='female', language="en")
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值