Make python code function as microphone using pyttsx3?

Question:

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 engine
engine = pyttsx3.init()

def Voice(text):
    # convert this text to speech
    engine.say(text)
    # play the speech
    engine.runAndWait()

# Set and get rate of the voice; how fast it speaks - Default is 
def getRate():
    # get details of speaking rate
    rate = 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 male
        engine.setProperty("voice", voices[0].id)
    elif gender == "female":
        # 1 is female
        engine.setProperty("voice", voices[1].id)
    else: 
        print("Only 'male' or 'female' is avalible. ")
        
# prints the different settings avalible
def 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":
            break
        if 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, sys
from pygame import mixer
import pygame._sdl2.audio as sdl2_audio

# initialize Text-to-speech engine
engine = pyttsx3.init()
mixer.init(devicename='CABLE Input (VB-Audio Virtual Cable)')

# Plays the text on your speakers
def voice(text):
    try:    
        # Save text to mp3 file
        engine.save_to_file(text, "voice.wav")
        # convert this text to speech
        engine.say(text)
        # play the speech
        engine.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 rate
    rate = 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 male
        engine.setProperty("voice", voices[0].id)
    elif gender == "female":
        # 1 is female
        engine.setProperty("voice", voices[1].id)
    else: 
        print("Only 'male' or 'female' is avalible. ")
        
# prints the different settings avalible
def 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 microphone
def 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 device

def setMic():
    device = input("Name of microphone?: " )
    mixer.init(devicename=device) #Initialize it with the correct device

def micPlay():
    try:
        mixer.music.load("voice.wav") #Load the mp3
        mixer.music.play() #Play it
        while mixer.music.get_busy():  # wait for music to finish playing
            time.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()
            break
        elif text[0] == "!":
            settings(text[1:])
        else:
            voice(text)
Asked By: Drunkduckling

||

Answers:

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 os
os.remove("filename.mp3")
Answered By: noah1400