【问题标题】:Speech to text in python with a WAV file使用 WAV 文件在 python 中语音到文本
【发布时间】:2019-07-21 19:40:48
【问题描述】:

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

帮助? :)

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

【问题讨论】:

  • 对我来说很好。
  • 退出代码 0 通常表示一切正常。
  • 你的代码适合我

标签: python speech-recognition google-speech-api speech-recognition-api


【解决方案1】:

好吧,我确实做到了。如果有人遇到同样的问题,我会发布对我有用的代码:

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

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

【讨论】:

  • 你好@Vincent。如何查看脚本的文本输出。我只得到:异常:进程以退出代码 0 结束
【解决方案2】:

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

  1. 在脚本范围内创建变量(即不在任何条件块内,例如在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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-23
    • 2010-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多