Impossible to use pyttsx3: No module named 'pywintypes', but pywin32 is installed

709 views Asked by At

I try to use speech synthesis in Python 3.9.13 [MSC v.1929 64 bit (AMD64)]. If I understand well, pyttxs3 is the dedicated module (thank you in advance for any possible alternative!), which I installed successfully:

c:\>pip install -U pyttsx3
Requirement already satisfied: pyttsx3 in c:\users\...\python39\site-packages (2.90)
Requirement already satisfied: comtypes in c:\users\...\python39\site-packages (from pyttsx3) (1.1.11)
Requirement already satisfied: pywin32 in c:\users\...\python39\site-packages (from pyttsx3) (304)
Requirement already satisfied: pypiwin32 in c:\users\...\python39\site-packages (from pyttsx3) (223)

but I cannot initialize the engine: when I do

>>> e = pyttsx3.init()
Traceback (most recent call last):
  File "C:\Users\...\Python39\site-packages\pyttsx3\__init__.py", line 20, in init
    eng = _activeEngines[driverName]
  File "C:\Program Files\...\lib\weakref.py", line 137, in __getitem__
    o = self.data[key]()
KeyError: None

During handling of the above exception, another exception occurred:
...
 File "C:\Users\...\Python39\site-packages\pyttsx3\drivers\sapi5.py", line 10, in <module>
    import pythoncom
  File "C:\Users\...\Python39\site-packages\pythoncom.py", line 2, in <module>
    import pywintypes
ModuleNotFoundError: No module named 'pywintypes'

I noticed that part of the scripts are in my Users\...\AppData\Local\Packages\PythonSoftwareFoundation... and some are in "C:\Program Files\WindowsApps\PythonSoftwareFoundation.... I wonder whether that might be the reason for the errors.

How could I fix this? (I also found that there are other modules, speech and pyttsx, which however appear to be for Python 2.7: they produce Syntax error: print "..." - did you mean print("...")? Is there a Python 3 version of speech or any other alternative?)

2

There are 2 answers

2
ROOP AMBER On

pyttxs3 is a little (actually very) glitched for example after i removed a part of my code which involved speaking something it still spoke my old code i removed the whole pyttxs3 from my code it still didn't work at last i had to uninstall the package. I used this function. You need to install pygame (it is a game making package but we will use it) and gtts i.e google text to speech

import os
from pygame import *
from gtts import *

def speak(text: str):
    try:
        tts_ = gTTS(text=text, lang='en')
        ran = random.randint(0, 1000000)
        audio_file = 'audio-' + str(ran) + '.mp3'
        tts_.save(audio_file)


        # Starting the mixer
        mixer.init()

        # Loading the song
        mixer.music.load("C:///Users/roopa/PycharmProjects/pokemon game/" + audio_file)

        # Start playing the song
        mixer.music.play()
        clock = time.Clock()
        # infinite loop
        while mixer.music.get_busy():
            clock.tick(60)
            
        mixer.music.unload()
        os.remove(audio_file)

    except gTTSError:
        print('unknown error')
7
Max On

Roop's answer didn't work out completely for me due to an error "Failed loading libmpg123-0.dll", but it enabled me to find the following working solution:

import gtts         # text to mp3 file
import random       # for random file name generation
import playsound    # to play mp3 file
import os           # to remove audio file

def say(text: str, block = True, lang = 'en'):
    """Text-to-speech synthesis using google TTS. If block=True,
        waits until the text is spoken. If False, return a cleanup
        function to delete the temporary audio file."""
    audio_file = f'audio-{random.randint(0, 1000000)}.mp3'
    gtts.gTTS(text, lang = lang).save(audio_file)
    playsound.playsound(audio_file, block = block)
    if block:
        os.remove(audio_file)
    else:
        print(f"Playing sound, don't forget to do: os.remove('{audio_file}')"
              "\n(You can do so by calling the returned function.)")
        return(lambda: os.remove(audio_file)) 

if __name__=='__main__':
    cleanup = say("Good morning, Max!")
    if cleanup: # if block = True, function returns None
        import time
        time.sleep(10)
        cleanup()

(It appears to be a known bug of playsound that the sound isn't played to the end if the script ends too early, therefore I added the sleep(10), but obviously you can do other stuff instead.)

That said, the question regarding pyttsx3 and pywin32 remains open.