Speak on Fly (app)

This is a script I made some time ago.

from gtts import gTTS
from io import BytesIO
import pygame
import time


def wait():
    while pygame.mixer.get_busy():
        time.sleep(.1)


def process_speak(text="", language='en'):
    ''' speaks without saving the audio file '''
    wait()
    mp3_fo = BytesIO()
    tts = gTTS(text, lang=language)
    tts.write_to_fp(mp3_fo)
    mp3_fo.seek(0)
    sound = pygame.mixer.Sound(mp3_fo)
    sound.play()
    wait()

def save_(name="myfile", text="", language='en'):
    ''' saves the audio file and then speaks '''
    global filecount

    tts = gTTS(text, lang=language)
    tts.save(f"{name}{filecount}.mp3")
    sound = pygame.mixer.Sound(f"{name}{filecount}.mp3")
    filecount+=1
    sound.play()
    wait()

def save_file(name="myfile", text="", language='en'):
    ''' saves the audio file and then speaks '''
    global filecount
    text = ",".join(text)
    tts = gTTS(text, lang=language)
    tts.save(f"{name}{filecount}.mp3")
    sound = pygame.mixer.Sound(f"{name}{filecount}.mp3")
    sound.play()
    wait()

def speak(text: list or str):
    ''' use speak as many lines are there into text '''
    if type(text) == list:
        for t in text:
            process_speak(t)
    elif type(text) == str:
        process_speak(text)

def save(text):
    for t in text:
        save_("myfile", t)
filecount = 0


def examples():
    global text
    guide = f"""
    {text=}
    Examples:
        speak("A simple text")
        speak(text) # where text is a multiline string converted into list with splitlines() or a list of strings
    
    Example of saving the text into a file
        save_file("onefile", text)""".splitlines()

    for x in guide:
        print(x)


pygame.init()
pygame.mixer.init()

# Provide a long text, making it a list
text = """I've always thought too much
it's like my brain cannot stop thinking
so I guess what could stop overthinking
""".splitlines()


speak("This is working")
speak(text)
examples()

Version with Tkinter GUI

import tkinter as tk
from tkinter import scrolledtext
from gtts import gTTS
import pygame
import tempfile
import os

class TextToSpeechGUI:
    def __init__(self, master):
        self.master = master
        master.title("Text-to-Speech GUI")
        master.geometry("800x600")

        # Initialize pygame mixer
        pygame.mixer.init()

        # Text area
        self.text_area = scrolledtext.ScrolledText(master, wrap=tk.WORD, width=60, height=20)
        self.text_area.pack(pady=20)

        # Buttons frame
        button_frame = tk.Frame(master)
        button_frame.pack(pady=10)

        # Play button
        self.play_button = tk.Button(button_frame, text="Play", command=self.play_text)
        self.play_button.pack(side=tk.LEFT, padx=10)

        # Save button
        self.save_button = tk.Button(button_frame, text="Save", command=self.save_audio)
        self.save_button.pack(side=tk.LEFT, padx=10)

        self.filecount = 0

    def play_text(self):
        text = self.text_area.get("1.0", tk.END).strip()
        if text:
            self.text_to_speech(text, play=True)

    def save_audio(self):
        text = self.text_area.get("1.0", tk.END).strip()
        if text:
            filename = self.text_to_speech(text, save=True)
            print(f"File saved as: {filename}")

    def text_to_speech(self, text, play=False, save=False):
        tts = gTTS(text, lang='en')
        
        if play:
            # Save to a temporary file
            with tempfile.NamedTemporaryFile(delete=False, suffix='.mp3') as tf:
                temp_filename = tf.name
                tts.save(temp_filename)

            # Play the audio
            pygame.mixer.music.load(temp_filename)
            pygame.mixer.music.play()

            # Wait for the audio to finish playing
            while pygame.mixer.music.get_busy():
                pygame.time.Clock().tick(10)

            # Clean up the temporary file
            pygame.mixer.music.unload()
            os.unlink(temp_filename)

        if save:
            filename = f"tts_output{self.filecount}.mp3"
            tts.save(filename)
            self.filecount += 1
            return filename

if __name__ == "__main__":
    root = tk.Tk()
    gui = TextToSpeechGUI(root)
    root.mainloop()

Version with pygame GUI


Subscribe to the newsletter for updates
Tkinter templates

Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Claude's Games

Arkanoid
Platform 2d

1. Memory game

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Advertisement