I was trying to create a basic personal assistant, just to learn a bit more about the Python language (I'm 16 so I haven't started programming in classes yet).
And I've run into a weird error telling me that a variable is undefined inside a function, however I'm pretty sure I've declared it, and it should accept it.
Here is my code.
# Importar Librerías
import speech_recognition as sr # Reconocimiento de voz.
from gtts import gTTS # Conversión de texto a MP3.
import playsound # Lectura de MP3.
# Declarar Variables
username = ""
myName = "Vewi"
microphone = sr.Recognizer()
tts = ""
audioNumber = 0 # Ésta es la variable declarada.
lang = "es-ES"
# Función Presentarse
def ImVewi():
audioText = ("Hola, soy " + myName + ". Mi trabajo será ayudarte. Para comunicarte conmigo, prueba a hablarle al micrófono. Ahora, te haré unas preguntas rápidas para poder mejorar tu experiencia.")
TextToSpeech(audioText)
ChangeUsername()
# Función Obtener Username
def ChangeUsername():
global audioText
with sr.Microphone() as source:
audioText = ("¿Cómo te llamas?")
TextToSpeech(audioText)
print("a")
audio = microphone.listen(source)
print("Listened")
try:
username = microphone.recognize_google(audio, language=lang)
audioText = ("Perfecto, ahora te llamaré " + username + ".")
TextToSpeech(audioText)
except sr.UnknownValueError:
audioText = ("Disculpa, no te he entendido. ¿Podrías repetirlo?")
TextToSpeech(audioText)
ChangeUsername()
except sr.RequestError:
audioText = ("Disculpa, se ha producido un error. ¿Podrías repetirlo?")
TextToSpeech(audioText)
ChangeUsername()
# Transformar Texto a Audio
def TextToSpeech(audioText): # Ésta es la función con el error.
audioNumber+=audioNumber # El error lo da en esta línea.
tts = gTTS(text=audioText, lang = lang)
tts.save("Audio/Speech"+str(audioNumber)+".mp3")
playsound.playsound("Audio/Speech"+str(audioNumber)+".mp3", True)
# Llamar Funciones
ImVewi()
I should create an MP3 file called "Speech1.mp3" as it doesn't let me overwrite previously created files by default, so it can't just be "Speech.mp3" or a predefined name.
In the terminal I get this problem:
Undefined variable 'audioNumber' // Line 58, column 5
It would also help me if someone knew another way to do this, or to overwrite previously created MP3 files.
I have been trying for a long time and I have not been able to solve it. Thanks in advance.
You have to add
global
to your variable inside the methodTextToSpeech()
Example code:
The reason for this error is that inside
TextToSpeech()
Python it thinks your variableaudioNumber
is a local variable (and you don't have it declared locally). You have to tell it that itaudioNumber
is global so that it looks for it in a scope beyond the function