pyTelegramBotAPI 和语音识别

时间:2020-12-22 21:35:42

标签: python-3.x speech-recognition wav ogg py-telegram-bot-api

我正在使用 pyTelegramBotAPI 构建 Telegram 机器人。该机器人应该从用户那里获取语音消息并使用 SpeechRecognition 库执行文本识别。据我所知,电报语音消息是 ogg 文件,而语音识别不支持 ogg,因此我需要将其转换为 wav 或 flac(或 SpeechRecognition 支持的任何其他格式)。我正在按照此处的建议进行操作 How to convert Telegram voice in a wave file in python

但是下面的代码...

@bot.message_handler(content_types=['voice', 'audio'])
def get_audio_messages(message):
    r = sr.Recognizer()
    
    file_info = bot.get_file(message.voice.file_id)
    downloaded_file = bot.download_file(file_info.file_path)
    with open('user_voice.ogg', 'wb') as new_file:
        new_file.write(downloaded_file)

    src_filename = 'user_voice.ogg'
    dest_filename = 'user_voice_output.flac'

    process = subprocess.run(['C:\\ffmpeg\\bin\\ffmpeg.exe', '-i', src_filename, dest_filename])
    if process.returncode != 0:
        raise Exception("Something went wrong")

    with open('user_voice_output.flac', 'rb') as user_audio:
        text = r.recognize_google(user_audio)
        bot.send_message(message.from_user.id, text)

    

... 仍然产生以下错误:

line 822, in recognize_google assert isinstance(audio_data, AudioData), "``audio_data`` must be audio data" 
    AssertionError: ``audio_data`` must be audio data

我是否遗漏了 ogg 到 flac 或 ogg 到 wav 的转换?

1 个答案:

答案 0 :(得分:0)

我在这里找到了答案https://s3.amazonaws.com/assets.datacamp.com/production/course_17718/slides/chapter2.pdf

import speech_recognition as sr    
user_audio_file = sr.AudioFile("user_voice_output.wav")
with user_audio_file as source:
    user_audio = r.record(source)
text = r.recognize_google(user_audio, language='en-US')