11 Text-to-Speech (TTS)

From Waveshare Wiki
Revision as of 09:45, 21 March 2024 by Eng52 (talk | contribs) (Created page with "<div class="wiki-pages jet-green-color"> Due to security considerations, it's not feasible to directly access audio devices through JupyterLab because of the environment's lim...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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.
Additionally, control over voice playback synchronization is managed through event objects.