11 Text to Speech (TTS)

From Waveshare Wiki
Jump to: navigation, search

Text-to-speech (TTS)

For security reasons, you don't have direct access to audio devices through JupyterLab (environmental limitations), and we don't have code blocks here for users to run.

The program here comes from the audio_ctrl.py of the main program of the product, and you can refer to the code here to understand how the main program of the product performs the text-to-speech function.

import pyttsx3 # import pyttsx3 library for text-to-speech functionality 
import threading # import threading module for creating threads

# Initialize pyttsx3 engine 
engine = pyttsx3.init()

# Create an event object to control the synchronization of voice playback 
play_audio_event = threading. Event()

# Set the engine property, here is the speed of voice playback, the higher the value, the faster the speed of speech 
engine.setProperty('rate', 180)

# Define a function to play the speech 
def play_speech(input_text): 
    engine.say(input_text) # Enter the text into the engine 
    engine.runAndWait() # Wait for the voice output to complete 
    play_audio_event.clear() # Clear the event to indicate that the voice playback is complete

# Define a function to play a voice in a new thread 
def play_speech_thread(input_text): 
    if play_audio_event.is_set(): # If there is already a voice in playback, return it directly without repeating it 
       return 
    play_audio_event.set() # Set an event to indicate that a new voice playback task starts 
    # Create a new thread and call play_ speech function to play speech 
    speech_thread = threading. Thread(target=play_speech, args=(input_text,)) 
    speech_thread.start() # Start a new thread and start playing voice

This code uses the pyttsx3 library to implement text-to-speech functionality, and uses the threading module to create a thread to play speech asynchronously. The play_speech() function is used to play the speech of the specified text in the main thread, while the play_speech_thread() function is used to play the voice in the new thread to avoid blocking the main thread. At the same time, the synchronization of voice playback is controlled by play_audio_event to ensure that only one voice is playing at the same time.