将文本保存到语音Python

时间:2018-04-17 06:26:31

标签: python text-to-speech

我正在尝试将文本结果保存到Windows上的文件中。我成功地说出来了(使用speak.Speak)。但是,保存文件没有这么幸运。

问题是找不到AudioOutputStream,尽管它being listed in the Microsoft docs

版本信息:Windows 10,Python 3.6

错误

Traceback (most recent call last):
  File "...\dd.py", line 87, in <module>
    speak.AudioOutputStream = filestream
  File "...\win32com\client\dynamic.py", line 565, in __setattr__
    self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
pywintypes.com_error: (-2147352573, 'Member not found.', None, None)

代码

from win32com.client import Dispatch
import win32api

speak = Dispatch("SAPI.SpVoice")
filestream = Dispatch("SAPI.SpFileStream")
filestream.open("out.wav", 3, False) 
for k in speak.GetAudioOutputs():
    print(k.GetDescription())
speak.AudioOutputStream = filestream
speak.Speak("test")
filestream.close()

2 个答案:

答案 0 :(得分:2)

我设法让它发挥作用。由于最初对这篇文章的答复很少,我相信为未来的访问者留下这个修复是非常有用的。

使用pip install comtypes安装库。它比python的本机comtype实现更加合作,不那么笨拙。

import comtypes.client

speak = comtypes.client.CreateObject("SAPI.SpVoice")
filestream = comtypes.client.CreateObject("SAPI.spFileStream")
filestream.open("out.wav", 3, False)
speak.AudioOutputStream = filestream 
speak.Speak("test")
filestream.close()

答案 1 :(得分:0)

我发现了这个问题,但 Neil 使用 comtypes 提供的解决方案对我不起作用,并给了我一个错误。

但是,他的原始解决方案确实适用于我的系统:

  • Windows 10 专业版,版本 19.0.19041 内部版本 19041
  • Python 3.8.1 64 位

我用它来为语音时钟创建 .wav 文件

import win32com.client

phrases = [
    "Zero",
    "One",
    "Two",
    "Three",
    "Four",
    "Five",
    "Six",
    "Seven",
    "Eight",
    "Nine",
    "Ten",
    "Eleven",
    "Twelve",
    "Thirteen",
    "Fourteen",
    "Fifteen",
    "Sixteen",
    "Seventeen", 
    "Eighteen",
    "Nineteen",
    "Twenty",
    "Thirty",
    "Fourty",
    "Fifty",
    "Hundred",
]

speaker = win32com.client.Dispatch("SAPI.SpVoice")
filestream = win32com.client.Dispatch("SAPI.SpFileStream")

def speak(phrase):
    speaker.speak(phrase)
    
def save_voice(phrase):
    filestream.open(".".join([phrase, "wav"]), 3, False)
    speaker.AudioOutputStream = filestream
    speaker.speak(phrase)
    filestream.close()

for phrase in phrases:
    save_voice(phrase)