11 Text-to-Speech (TTS)
Due to security considerations, it's not feasible to directly access audio devices through JupyterLab because of the environment's limitations. Therefore, the code blocks provided here are not intended for execution by users.
The programs presented here originate from the product's main program file, audio_ctrl.py. You can refer to these code snippets to gain insight into how the product's main program facilitates text-to-speech functionality.
import pyttsx3 # Importing the pyttsx3 library for text-to-speech functionality import threading # Importing the threading module for creating threads # Initializing the pyttsx3 engine engine = pyttsx3.init() # Creating an event object to control the synchronization of audio playback play_audio_event = threading.Event() # Setting the speed of voice playback engine.setProperty('rate', 180) # Defining a function to play voice for the given text def play_speech(input_text): engine.say(input_text) # Inputting the text into the engine engine.runAndWait() # Waiting for the voice output to complete play_audio_event.clear() # Clearing the event to indicate voice playback is complete def play_speech_thread(input_text): if play_audio_event.is_set(): # If a voice is already being played, return immediately to avoid overlapping playback return play_audio_event.set() # Setting the event to indicate a new voice playback task has started # Creating a new thread to play voice using the play_speech function speech_thread = threading.Thread(target=play_speech, args=(input_text,)) speech_thread.start() # Starting the new thread to begin voice playback
The code utilizes the pyttsx3 library to achieve text-to-speech conversion and employs the threading module to create a thread for asynchronous voice playback. The function "play_speech()" is designed to play the specified text's voice in the main thread, while "play_speech_thread()" function facilitates voice playback in a new thread to prevent blocking the main thread.
Also, "play_audio_event" controls the synchronization of voice playback to ensure that only one voice is playing at a time.