I am building a Telegram bot using pyTelegramBotAPI. The bot is supposed to get a voice message from a user and perform text recognition using SpeechRecognition library. As I know telegram voice messages are ogg files and speechrecognition does not support ogg, hence I need to convert it either to wav or to flac (or any other format that is supported by SpeechRecognition). I am doing it as suggested here How to convert Telegram voice in a wave file in python
However the following code...
@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)
... still yields the following error:
line 822, in recognize_google assert isinstance(audio_data, AudioData), "``audio_data`` must be audio data"
AssertionError: ``audio_data`` must be audio data
Am I missing something about ogg to flac or ogg to wav conversion?
I found the answer here 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')