使用 WAV 文件将语音转为 python 中的文本

Speech to text in python with a WAV file

我尝试转换 WAV 文件中的语音,但我被困在这里。很多教程都提供相同的代码,但对我不起作用。这是:

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

"hello_world.wav" 文件与代码在同一个目录中。我没有任何错误。控制台:

C:\Users\python.exe "D:/voice_recognition.py"
Exception:

Process finished with exit code 0

帮忙? :)

(对不起,如果我的英语不好)

好的,我真的成功了。如果有人遇到同样的问题,我 post 对我有用的代码:

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

可能是因为我用了'而不是"。

您的原始代码已关闭;可能发生的情况是您的源变量可能具有 with … as source: 块的写入范围。通过结束 with 块;您还取消了为该块创建的变量。如果这是问题所在,您可以:

  1. 在脚本范围内创建变量(即不在任何条件块内,例如 r = sr.Recognizer() 之后),并且只在 with
  2. 内为其赋值
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. 在音频文件在范围内时执行所有处理
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. 正如您在上面接受的解决方案中所做的那样;删除 with 块并展平您的代码结构。
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))