语音识别不生成文件

Speech recognition not fouding a file

我知道这可能是一件容易的事,但似乎有些事情不起作用。我正在尝试创建一个简单的“语音到文本”脚本,并且我正在使用库“SpeechRecognition”。这是代码:

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')

然而,当我 运行 te 软件时(没有第一次尝试,除了)它给我这个错误:

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'

我的目录是:

Sbobinare
|__ main.py
|__ speech.wav

我什至尝试将 .wav 文件放在不同的目录中,但它一直给我这个错误。有人知道吗?

os.listdir 仅列出文件在该目录中的相对路径,因此代码不会在您执行脚本的目录中找到该文件。如果你只是加入“diR”和“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')