I've use pydub to output a file(chop the file into shorter one), everything is great, but the bitrate has changed from 256k to 124k(why I will get this number instead 128k?). I know that AudioSegment has an argument to set bitrate, but I just want the same bitrate instead manually set every time. Any way to fix this issue?
Asked
Active
Viewed 5,336 times
2 Answers
13
This has mainly to do with ffmpeg/avlib, but you can pass a flag to the AudioSegment().export()
method to specify the bitrate you'd like:
from pydub import AudioSegment
from pydub.utils import mediainfo
source_file = "/path/to/sound.mp3"
original_bitrate = mediainfo(source_file)['bit_rate']
sound = AudioSegment.from_mp3(source_file)
sound.export("/path/to/output.mp3", format="mp3", bitrate=original_bitrate)

Jiaaro
- 74,485
- 42
- 169
- 190
-
I know the api you provide can export the bitrate you want, but I don't know what bitrate I should give if I don't know the input file's bitrate. I only want the bitrate of input and output file be the same, instead of giving a certain value to it. – Leo Hsieh Nov 21 '15 at 02:09
-
@LeoHsieh, the line with "original_bitrate = mediainfo(source_file)['bit_rate'] " will give you the original bitrate, then at the last line, it will apply that original bitrate to your mp3 file. – Alejandro Jan 27 '23 at 01:45
3
I was unable to use the example above using the mediainfo
object. I just found the way to calculate the bitrate for WAV files here and used that.
Translating it into python and pydub, and assuming the pydub object is called wav
you would get that:
bitrate = str((wav.frame_rate * wav.frame_width * 8 * wav.channels) / 1000)
Then you could pass it forward into the export function and not set it manually. Hope it helps :)

Almog Cohen
- 1,283
- 1
- 13
- 12