将文本文件中每行文字转为语音

 文本文件

代码

from comtypes.client import CreateObject
import win32com.client as win

try:
    from comtypes.gen import SpeechLib  # comtypes
except ImportError:
    # Generate the SpeechLib lib and any associated files
    engine = CreateObject("SAPI.SpVoice")
    stream = CreateObject("SAPI.SpFileStream")
    from comtypes.gen import SpeechLib

speak = win.Dispatch("SAPI.SpVoice")
engine = CreateObject("SAPI.SpVoice")
stream = CreateObject('SAPI.SpFileStream')

infile = r'D:\testdata\Voices_text.txt'
outfile = 'D:/testdata/'

f = open(infile, 'r', encoding='utf-8')
while True:
    LineData = f.readline()  # 按行读取数据
    if not LineData:
        break
    # 截取LineData首部第1-4个字符作为编号
    stnum = LineData[:6]
    stream.Open(outfile + stnum + ".wav", SpeechLib.SSFMCreateForWrite)
    engine.AudioOutputStream = stream
    # 截取LineData第4个至尾部的字符作为语音内容
    mytxt = LineData[4:]
    # speak.Speak(mytxt)  # 朗读
    engine.speak(mytxt)
    stream.close()
f.close()  # 关闭文本文件

结果

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值