2

I am saving text-to-speech audio to file using the following code:

from comtypes.client import CreateObject
from comtypes.gen import SpeechLib

engine = CreateObject("SAPI.SpVoice")
stream = CreateObject("SAPI.SpFileStream")
stream.Open('audio.mp3', SpeechLib.SSFMCreateForWrite)
engine.AudioOutputStream = stream
engine.speak(text)
stream.Close()

Occasionally, the file created cannot be played and may have size zero - although no errors occur. I found an example of input text that was used during one of these failures (too long to include here) and the result was reproducible, but it has no obviously problematic features.

I haven't been able to find out how to detect errors in the code above or determine what might be causing the problem. Ideally, I would like to resolve the issue, but detecting the problem to enable me to deal with it would suffice. How can I achieve this?

Ninjakannon
  • 3,751
  • 7
  • 53
  • 76

1 Answers1

2

Well, I don't know why it failed silently, but when I ran it, it raised: ImportError: Cannot import name SpeechLib.

I then went to trusty ole Google, and found this SO question:

Can't save to wav from python, can't import SpeechLib from comtypes.gen, what next?

So your code should look like:

from comtypes.client import CreateObject

text="Hi there, how are you?"
engine = CreateObject("SAPI.SpVoice")
stream = CreateObject("SAPI.SpFileStream")
from comtypes.gen import SpeechLib
stream.Open('audio.mp3', SpeechLib.SSFMCreateForWrite)
engine.AudioOutputStream = stream
engine.speak(text)
stream.Close()

This worked and saved a audio.mp3 file.

IronManMark20
  • 1,298
  • 12
  • 28
  • Thanks for your input. My code works fine more than 99% of the time and doesn't produce the error you describe. Sometimes, however, the audio file is broken, and that's what I don't know how to fix. – Ninjakannon May 22 '15 at 23:07
  • Thinking back, I recall that I did in fact use the SO question/answer you link when I first installed the comtypes library. However, after running the code once, I could use the code as in my question without error. – Ninjakannon May 22 '15 at 23:41
  • I got similar error which was fixed by installing specific version `pip install pyttsx3==2.6` – Kundan Oct 17 '20 at 06:56