How to generate wav with G.711alaw from a mp3 file using pydub library?

1.7k views Asked by At

I am trying to generate a wav file with G. 711 alaw companding from a mp3 file using Pydub library. The wav file is getting generated but it is not resampled to frequency 8 kHz. I have tried following code:

from_path = '/home/nikhil/Music/m1.mp3' #this is a mp3 file
to_path = '/home/nikhil/Music/m1.wav' #resulted file
from_format = 'mp3'
to_format = 'wav'
params = ["-acodec", "pcm_alaw", "-ar", "8000"]
AudioSegment.from_file(from_path, from_format).export(to_path, format=to_format, parameters=params)

Can someone help me?

2

There are 2 answers

0
user3073001 On

Changing

to_format = 'pcm'  

to

to_format = 'wav' 

resolves the problem in the replay

1
Jiaaro On

I was looking over the code in the export method and I realized that ffmpeg is not used when the output format is "wav".

Since wav is used internally it just writes the in-memory version of the audio directly to disk (this was done to make ffmpeg an optional dependency, if you only need wav support you don't need to install it).

I have 2 ideas that may allow you to get around this issue:

  1. Use a different format kwarg, like "pcm". I'm not sure if this will work, and I don't have ffmpeg on my current machine to test, but definitely worth a try.

    from_path = '/home/nikhil/Music/m1.mp3' #this is a mp3 file
    to_path = '/home/nikhil/Music/m1.wav' #resulted file
    from_format = 'mp3'
    to_format = 'pcm'
    params = ["-acodec", "pcm_alaw", "-ar", "8000"]
    AudioSegment.from_file(from_path, from_format).export(to_path, format=to_format, parameters=params)
    
  2. Use pydub's internal mechanism for resampling to 8kHz: Again, I can't test this right at the moment...

    from_path = '/home/nikhil/Music/m1.mp3' #this is a mp3 file
    to_path = '/home/nikhil/Music/m1.wav' #resulted file
    
    seg = AudioSegment.from_mp3(from_path)
    seg = seg.set_frame_rate(8000)
    seg.export(to_path, format="wav")