'Speech recognition not fouding a file
I Know that it is probably an easy task, but something seems not to work. I'm trying to create a simple "speech to text" script and I'm using the library "SpeechRecognition". This is the code:
import speech_recognition as sr
import os
r = sr.Recognizer()
diR = input('Path with the file: ')
rec = ''
for e in os.listdir(diR):
if '.wav' in e or '.mp4' in e:
rec = e
print('the file is: ',rec)
# try:
with sr.AudioFile(rec) as source:
audio_text = r.listen(source)
try:
# using google speech recognition
text = r.recognize_google(audio_text, language ="it-IT")
print('Converting audio transcripts into text ...')
print(text)
except:
print("A problem occured ... Try again")
# except FileNotFoundError:
# print('no file found')
However when I run te software (without the first try,except) it gives me this error:
Path with the file: C:/vscode/PYTHON/Sbobinare
the file is: speech.wav
Traceback (most recent call last):
File "c:\vscode\PYTHON\Sbobinare\main.py", line 12, in <module>
with sr.AudioFile(rec) as source:
File "C:\Python310\lib\site-packages\speech_recognition\__init__.py", line 203, in __enter__
self.audio_reader = wave.open(self.filename_or_fileobject, "rb")
File "C:\Python310\lib\wave.py", line 509, in open
return Wave_read(f)
File "C:\Python310\lib\wave.py", line 159, in __init__
f = builtins.open(f, 'rb')
FileNotFoundError: [Errno 2] No such file or directory: 'speech.wav'
The directory in my case is:
Sbobinare
|__ main.py
|__ speech.wav
I even tryied putting the .wav file in different directory but it keeps giving me this error. Anyone has any idea?
Solution 1:[1]
os.listdir just lists the files' relative path in that directory, so the code won't find the file in the directory you are executing the script from. Everything should work if you just join "diR" and "rec":
import speech_recognition as sr
import os
r = sr.Recognizer()
diR = input('Path with the file: ')
rec = ''
for e in os.listdir(diR):
if '.wav' in e or '.mp4' in e:
rec = e
print('the file is: ',rec)
# Modified here !!
rec = os.path.join(diR, rec)
# try:
with sr.AudioFile(rec) as source:
audio_text = r.listen(source)
try:
# using google speech recognition
text = r.recognize_google(audio_text, language ="it-IT")
print('Converting audio transcripts into text ...')
print(text)
except:
print("A problem occured ... Try again")
# except FileNotFoundError:
# print('no file found')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Giovanni Tardini |