Речь к тексту в Python с WAV-файлом

Я пытаюсь преобразовать речь в файл 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

Помогите?:)

(Извините, если мой английский плох)

3 ответа

Хорошо, я действительно заставил это работать. Я отправляю код, который работает для меня, если у кого-то есть такая же проблема:

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

Может быть, это потому, что я использовал "вместо".

Вместоaudio = r.record(source)использоватьaudio = r.listen(source)это сработало для меня..

вот ссылка откуда взял. связь

Your original code is close; what might be happening is your source variable could have the write scope of the with … as source: block. By ending the block; you're also unsetting the variables created for that block. If this is the issue, you could:

  1. Create your variables at the script scope (i.e. not within any conditional blocks, such as after r = sr.Recognizer()), and only assign it value within the block
      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. Perform all your processing while the audio file is in-scope
      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. As you've done in the accepted solution above; remove the with block and flatten your code structure.
      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))
Другие вопросы по тегам