Running functions simultaneously in Python3

Asked

Viewed 157 times

3

I have a snippet of a code that performs "text to Speech", but to see the print() function I have to wait for the playsound() function to end. Is there any way to make the script run the print() function while playsound() is playing? Create an object?

from gtts import gTTS
from playsound import playsound

#Funcao responsavel por falar 
def cria_audio(audio):
    tts = gTTS(audio,lang='pt-br')
    #Salva o arquivo de audio
    tts.save('hello.mp3')
    #Da play ao audio
    playsound('hello.mp3')
    print("Seu áudio está sendo reproduzido.")

1 answer

2

I did, all you have to do is create a new thread:

import threading
import time

def thread_function(name):
  print("Thread {}: Comecando".format(name))
  time.sleep(3)
  print("Thread {}: Terminando".format(name))

x = threading.Thread(target=thread_function, args=(1,))
print("Main: Antes da thread comecar a executar")
x.start()
print("Main: Continuando")
print("Main: Tudo pronto")

Run the above code and you will have as output:

Main: Antes da thread comecar a executar
Thread 1: Comecando
Main: Continuando
Main: Tudo pronto
Thread 1: Terminando

Note that the code arrives at the last print before the function thread_function finish running. Soon all you need to do is run the function playsound in a different thread. In this code above I simulated the audio being played with the function sleep.

A thread is basically a process that will run in parallel to the main program to learn more about threads and how to use them in python I recommend the following references:

explanation of threads in stackoverflow

thread in python

Deepening in python thread

This subject is a very interesting subject and as complex as you want to delve into but if you are wanting to become a better develop highly recommend studying more on the subject of multi-thread programming.

  • Very interesting. Later when I get back from work I will test this code

Browser other questions tagged

You are not signed in. Login or sign up in order to post.