1

I'm using pyttsx3 to convert text to speech.

import pyttsx3

def tts(text):
    engine = pyttsx3.init()
    engine.say(text)
    engine.runAndWait()

but the problem is that I can't save the sound to a file (which is so weird for a library like this).
I've tried some other alternatives like espeak which is the driver for pyttsx but the sound was bad even after tweaking some options.
If you have any suggestions of how can I save the sound or names of other offline libraries offering good speech quality (even with other programming languages) that would be so helpful.
Thank you.

zguesmi
  • 321
  • 1
  • 11

1 Answers1

0

This may be late answer but I hope it will be useful :)

# pip install comtypes
import pyttsx3
engine = pyttsx3.init()
voices = engine.getProperty('voices')

voiceList = []
for voice in voices:
    voiceList.append(voice.name)

print("Voice List: " ,voiceList)
def playItNow(textf, filename, useFile = True, rate = 2, voice = voiceList[0]):
    from comtypes.client import CreateObject
    engine = CreateObject("SAPI.SpVoice")
    engine.rate = rate # can be -10 to  10

    for v in engine.GetVoices():
        if v.GetDescription().find(voice) >= 0:
            engine.Voice = v
            break
    else:
        print("Voice not found")

    if useFile:
        datei = open(textf, 'r',encoding="utf8")
        text = datei.read()
        datei.close()
    else:
        text = textf

    stream = CreateObject("SAPI.SpFileStream")
    from comtypes.gen import SpeechLib

    stream.Open(filename, SpeechLib.SSFMCreateForWrite)
    engine.AudioOutputStream = stream
    engine.speak(text)
    stream.Close()


    import winsound 
    winsound.PlaySound(filename,  winsound.SND_FILENAME)    

playItNow("TextFile.txt", "test_2.wav", useFile= False, rate = -1)
Trees
  • 1,245
  • 10
  • 20