Speech to text in python with a WAV file

Question:

I try to convert a speech in a WAV file but I’m stuck here. A lot of tutorial give the same code but it doesn’t work for me. Here it is:

import speech_recognition as sr
r = sr.Recognizer()

with sr.AudioFile("hello_world.wav") as source:
    audio = r.record(source)
try:
    s = r.recognize_google(audio)
    print("Text: "+s)
except Exception as e:
    print("Exception: "+str(e))

The “hello_world.wav” file is in the same repertory than the code. I don’t have any error. The console:

C:Userspython.exe "D:/voice_recognition.py"
Exception:

Process finished with exit code 0

Help? 🙂

(Sorry if my English is bad)

Asked By: Bojack

||

Answers:

Okay I actually made it work. I post the code that work for me if someone have the same problem:

import speech_recognition as sr
r = sr.Recognizer()

hellow=sr.AudioFile('hello_world.wav')
with hellow as source:
    audio = r.record(source)
try:
    s = r.recognize_google(audio)
    print("Text: "+s)
except Exception as e:
    print("Exception: "+str(e))

Maybe it was because I used ‘ instead of “.

Answered By: Bojack

Your original code is close; what might be happening is your source variable could have the write scope of the with … as source: block. By ending the with block; you’re also unsetting the variables created for that block. If this is the issue, you could:

  1. Create your variables at the script scope (i.e. not within any conditional blocks, such as after r = sr.Recognizer()), and only assign it value within the with block
import speech_recognition as sr
r = sr.Recognizer()
audio = False

with sr.AudioFile("hello_world.wav") as source:
    audio = r.record(source)
try:
    s = r.recognize_google(audio)
    print("Text: "+s)
except Exception as e:
    print("Exception: "+str(e))
  1. Perform all your processing while the audio file is in-scope
import speech_recognition as sr
r = sr.Recognizer()

with sr.AudioFile("hello_world.wav") as source:
    audio = r.record(source)
    try:
        s = r.recognize_google(audio)
        print("Text: "+s)
    except Exception as e:
        print("Exception: "+str(e))
  1. As you’ve done in the accepted solution above; remove the with block and flatten your code structure.
import speech_recognition as sr
r = sr.Recognizer()
audio = r.record(sr.AudioFile("hello_world.wav"))

try:
    s = r.recognize_google(audio)
    print("Text: "+s)
except Exception as e:
    print("Exception: "+str(e))
Answered By: crampus

Instead of audio = r.record(source)
make use of audio = r.listen(source)
it worked for me..

here is the link from where I got it. link

Answered By: Ramnath H Mallya