Hello I often have the trouble of not being able to speak with my friends over discord at night as my better half sleeps right behind me. Is there a way that I can use the small code I made here to "speak" for me when that happens.The TTS function on discord is not an option as it is a large server and will speak to everyone. :)

import pyttsx3# initialize Text-to-speech engineengine = pyttsx3.init()def Voice(text):# convert this text to speechengine.say(text)# play the speechengine.runAndWait()# Set and get rate of the voice; how fast it speaks - Default is def getRate():# get details of speaking raterate = engine.getProperty("rate")print(rate)def setRate(rate):# setting new voice rate (faster)engine.setProperty("rate", rate)# String gender of the voice: male, female, or neutral. Defaults to None if unknown.def getGender():gender = engine.getProperty("voice")print(gender)def setGender():gender = input("Pick a gender for TTS; male/female: ")voices = engine.getProperty("voices")if gender == "male":# 0 is maleengine.setProperty("voice", voices[0].id)elif gender == "female":# 1 is femaleengine.setProperty("voice", voices[1].id)else: print("Only 'male' or 'female' is avalible. ")# prints the different settings avalibledef help():print("These commands are avalible:---------")print(" !exit")print(" !setgender")print(" !getGender")print(" !setrate")print(" !getrate")def settings(text):if text == "help":help()elif text == "setgender":setGender()elif text == "getgender":getGender()elif text == "setrate":try:rate = int(input("Set rate?: "))setRate(rate)except ValueError:print("Only Integers allowed!") elif text == "getrate":getRate()else: print("Wrong commande or none given. ")if __name__ == '__main__':text = ""print("Hello and welcome to my TTS program! Type '!help' for commands.")while text != "!exit":text = input("Enter Text: ")if text == "!exit":breakif text[0] == "!":settings(text[1:])else:Voice(text)

Edit:-------------------------------------------------

So with some changes I made it work, with some help from noah1400 The changes can be seen udnerneath and for some reason didn't work well with the mp3 format as it would have some encoding problems or something. Changing the format to .wav solved the problem.

import os, time, pyttsx3, sysfrom pygame import mixerimport pygame._sdl2.audio as sdl2_audio# initialize Text-to-speech engineengine = pyttsx3.init()mixer.init(devicename='CABLE Input (VB-Audio Virtual Cable)')# Plays the text on your speakersdef voice(text):try: # Save text to mp3 fileengine.save_to_file(text, "voice.wav")# convert this text to speechengine.say(text)# play the speechengine.runAndWait()except Exception as e:print("Oops!", sys.exc_info()[0], " ", e , " occurred.")finally:micPlay()# Set and get rate of the voice; how fast it speaks - Default is def getRate():# get details of speaking raterate = engine.getProperty("rate")print(rate)def setRate(rate):# setting new voice rate (faster)engine.setProperty("rate", rate)# String gender of the voice: male, female, or neutral. Defaults to None if unknown.def getGender():gender = engine.getProperty("voice")print(gender)def setGender():gender = input("Pick a gender for TTS; male/female: ")voices = engine.getProperty("voices")if gender == "male":# 0 is maleengine.setProperty("voice", voices[0].id)elif gender == "female":# 1 is femaleengine.setProperty("voice", voices[1].id)else: print("Only 'male' or 'female' is avalible. ")# prints the different settings avalibledef help():print("These commands are avalible:---------")print(" !exit")print(" !getmic")print(" !setmic")print(" !setgender")print(" !getGender")print(" !setrate")print(" !getrate")#Used to play the sound though a virtual microphonedef getMic():mixer.init() # Initialize the mixer, this will allow the next command to work# Returns playback devices, Boolean value determines whether they are Input or Output devices.print("Inputs:", sdl2_audio.get_audio_device_names(True))print("Outputs:", sdl2_audio.get_audio_device_names(False))mixer.quit() # Quit the mixer as it's initialized on your main playback devicedef setMic():device = input("Name of microphone?: " )mixer.init(devicename=device) #Initialize it with the correct devicedef micPlay():try:mixer.music.load("voice.wav") #Load the mp3mixer.music.play() #Play itwhile mixer.music.get_busy(): # wait for music to finish playingtime.sleep(2)except Exception as e:print("Oops!", sys.exc_info()[0], " ", e , " occurred.")finally:mixer.music.unload()def settings(text):if text == "help":help()elif text == "getmic":getMic()elif text == "setmic":setMic()elif text == "setgender":setGender()elif text == "getgender":getGender()elif text == "setrate":try:rate = int(input("Set rate?: "))setRate(rate)except ValueError:print("Only Integers allowed!") elif text == "getrate":getRate()else: print("Wrong commande or none given. ")if __name__ == '__main__':text = ""print("Hello and welcome to my TTS program! Type '!help' for commands.")while text != "!exit":text = input("Enter Text: ")if text == "!exit":mixer.quit()breakelif text[0] == "!":settings(text[1:])else:voice(text)
1

Best Answer


Save your tts to a mp3 file

engine.save_to_file(text, "filename.mp3")

And then follow this thread.After that delete the file

import osos.remove("filename.mp3")