Search code examples
pythonmultithreadingwin32comsapi

Using win32client SAPI.SpVoice with multi-threading leads to pywintypes.com_error


I am trying to use a thread with wincl's built-in voice system. However I am running into this error:

pywintypes.com_error: (-2147221008, 'CoInitialize has not been called.', None, None)

which I can't seem to decipher.

Here is my code:

import win32com.client as wincl
import time, threading


def ten_second_timer():
    t =threading.Timer(10, ten_second_timer)
    speak = wincl.Dispatch("SAPI.SpVoice")
    speak.Speak("10 seconds have passed")
    t.start()


t =threading.Thread(target = ten_second_timer)
t.start()

Solution

  • You need to call pythoncom.CoInitialize or pythoncom.CoInitializeEx in a non-main thread to be able to use COM in it.