Skip to content

Instantly share code, notes, and snippets.

@theriley106
Last active November 4, 2023 12:06
Show Gist options
  • Save theriley106/9d3cf6df59399f65ba67271490274153 to your computer and use it in GitHub Desktop.
Save theriley106/9d3cf6df59399f65ba67271490274153 to your computer and use it in GitHub Desktop.
Windows Python Text-To-Speech
import os
# Be sure to import os into your script
'''
If you run the following command in the terminal, it will speak the words "testing to see if this works properly"
PowerShell -Command "Add-Type -AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak('testing to see if this works properly');"
This python script generates this command with whatever text is passed to the speak function
'''
randomString = "Hello Matt!"
def speak(stringOfText):
# This function will make windows say whatever string is passed
# You can copy and paste this function into any script, and call it using: speak("Random String")
# Be sure to import os into any script you add this function to
stringOfText = stringOfText.strip()
# Removes any trailing spaces or new line characters
stringOfText = stringOfText.replace("'", "")
# Removes all single quotes by replacing all instances with a blank character
stringOfText = stringOfText.replace('"', "")
# Removes all double quotes by replacing all instances with a blank character
command = '''"PowerShell -Command "Add-Type -AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak('{}');"'''.format(stringOfText)
# This is just a really long command that tells windows to say a text out loud
# At the end I am adding in the stringOfText parameter to the command
os.system(command)
# This runs the command as if you opened up a terminal and typed it in
speak(randomString)
speak("testing 1 2 3 4 5")
@osamaafzall
Copy link

That is really great command to use in windows
thank you .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment