How to convert Telegram voice in a wave file in py

2020-05-01 07:14发布

问题:

I'm trying to save a Telegram voice file in a wave audio file using soundfile library:

def ReceiveVoice(bot, update, user_data):

   voice = bot.getFile(update.message.voice.file_id)
   voice.download('file.ogg')
   data, samplerate = sf.read('file.ogg')
   sf.write('file.wav', data, samplerate)

But I'm receiving the following error:

File "C:\Python27\lib\site-packages\soundfile.py", line 257, in read
subtype, endian, format, closefd) as f:
File "C:\Python27\lib\site-packages\soundfile.py", line 624, in __init__
self._file = self._open(file, mode_int, closefd)
File "C:\Python27\lib\site-packages\soundfile.py", line 1179, in _open
"Error opening {0!r}: ".format(self.name))
File "C:\Python27\lib\site-packages\soundfile.py", line 1352, in _error_check
raise RuntimeError(prefix + _ffi.string(err_str).decode('utf-8', 'replace'))
RuntimeError: Error opening 'file.ogg': File contains data in an unimplemented format.

回答1:

You could try to use ffmpeg to convert from ogg to wav by executing the following command line using python's module subprocess.

import subprocess
src_filename = 'captured.ogg'
dest_filename = 'output.wav'

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


回答2:

Try this

import soundfile as sf
data, samplerate = sf.read(input_ogg)
sf.write(output_wav, data, samplerate)