Saturday, December 5, 2009

Let Python Speak using COM

What I have wanted to try and do is create a .Net assembly, make it COM accessible, and call it from Python through COM with pyWin32. There are plenty examples out on the web getting this to work for a simple math class or to call to Microsoft Excel. What I thought would be more interesting is to create a .Net assembly to expose the SpeechSynthesizer class so you could send string phrases from Python and have them spoken by the computer. I think that is a cooler example than a Microsoft Excel integration.

Prerequisites:
Python library for Windows: pyWin32
Visual Studio 2005 or greater (I used Microsoft Visual C# 2008 Express Edition)

Step 1. Create the .Net interface and class in a .Net Class Library (DLL)



Step 2. In the class project be sure to select COM Interop



Step 3. Register the .Net Assembly as a COM component from its build location


regasm SolidCode.Speech.dll /tlb: SolidCode.Speech.tlb

Step 4. Run this simple program from Python.

>>> import win32com.client
>>> speech = win32com.client.Dispatch("SolidCode.Speech")
>>> speech.speak('Hello world');

Step 5. Enjoy.

0 comments: