1

My problem is actually weird. My program runs good at some times but some time it speaks out what I have not asked for. for example: I said "hello" it says the time when I did not ask the time at all. Also when it does not recognize any speech from the user it speaks out the time. And when I ask what is the date it says the date but then it shows a error message

I have tried to switch around the if statements and i don't know much about speech recognition so did not try around much changes

import os
import time
from datetime import date
import playsound
import speech_recognition as sr 
from gtts import gTTS

def speak(text):
    tts = gTTS(text=text, lang="en")
    filename = "voice.mp3"
    tts.save(filename)
    playsound.playsound(filename)


def get_audio():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        audio = r.listen(source)
        said = ""

        try:
            said = r.recognize_google(audio)
            print(said)
        except Exception as e:
            print("Exception: " + str(e))
    return said

text = get_audio()

today = date.today()
t = time.localtime()
current_time = time.strftime("%H:%M", t)
d2 = today.strftime("%B %d, %Y")

if "hello" in text:
    speak("hello sir")

if "date" in text:
    speak("the date is: " + d2)

if "what's the time" or "what is the time" in text:
    speak("The time is: " + current_time)

The error message it shows when I say ask the date:

Traceback (most recent call last):
File "d:/python programs/hello.py", line 42, in <module>
speak("The time is: " + current_time)
File "d:/python programs/hello.py", line 11, in speak
tts.save(filename)
File "E:\python\lib\site-packages\gtts\tts.py", line 248, in save
with open(str(savefile), 'wb') as f:PermissionError: [Errno 13] Permission denied: 'voice.mp3'

When it does not recognize the voice of the user and returns a exception: it says out the time

These are all of the problems with the program.

  • Trying to open `voice.mp3` relative to cwd of the process might mean (and in this case likely does) mean it tries to write somewhere the process (user under which it runs) cannot write to (or cannot open already existing file (another session for instance) for writing). Errors passed from the OS can usually (and should at least initially) be taken for their face value. If file cannot be found or access is denied, usually you are not where/who you thing you are, or there could be a typo in filename.../ – Ondrej K. Sep 07 '19 at 14:30

1 Answers1

0

Generate unique filename instead of "voice.mp3" every time:

import uuid
filename = str(uuid.uuid4()) + ".mp3"
Nikolay Shmyrev
  • 24,897
  • 5
  • 43
  • 87
  • The thing is every time the computer speaks it makes a new .mp3 file and it does not delete it after the program ends.It would be good if it would delete the files after the program ends – uravgcodddingnoob Sep 08 '19 at 10:13