1

我尝试将语音转换为 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

帮助?:)

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

4

2 回答 2

4

好吧,我真的让它工作了。如果有人遇到同样的问题,我会发布对我有用的代码:

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

也许是因为我用了'而不是'。

于 2019-02-28T10:50:25.447 回答
0

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

  1. 在脚本范围内创建变量(即不在任何条件块内,例如 after ),并且只在块r = sr.Recognizer()内为其赋值with
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))
于 2021-09-01T03:50:27.830 回答