Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python library to split and join mp3 files

Tags:

python

mp3

There are a lot of libs to work with mp3 tags, but I need just 2 functions - split mp3 file in 2 parts and the second one to merge 5 mp3.

Can you suggest anything? Thanks!

like image 826
user355745 Avatar asked Jun 01 '10 18:06

user355745


People also ask

How do I join MP3 files in Python?

First, we write a helper function to get an extension of any file with Python, we'll use this to get the extension of the audio file automatically so we can pass it to PyDub. Second, we load the audio files using the AudioSegment. from_file() method which expects the audio path, and the extension.

What is the name of the library used to play MP3 files in Python?

Play Mp3 Files With Python Using the playsound Package One simple way to play an mp3 file using Python is with the help of playsound library.


2 Answers

I wrote a library (pydub) for pretty much this exact use case:

from pydub import AudioSegment  sound = AudioSegment.from_mp3("/path/to/file.mp3")  # len() and slicing are in milliseconds halfway_point = len(sound) / 2 second_half = sound[halfway_point:]  # Concatenation is just adding second_half_3_times = second_half + second_half + second_half  # writing mp3 files is a one liner second_half_3_times.export("/path/to/new/file.mp3", format="mp3") 

Adding a silent gap

If you'd like to add silence between parts of a sound:

two_sec_silence = AudioSegment.silent(duration=2000) sound_with_gap = sound[:1000] + two_sec_silence + sound[1000:] 
like image 127
Jiaaro Avatar answered Oct 08 '22 17:10

Jiaaro


Have a look at the MP3 file structure on Wikipedia. Use binary read mode in python to edit the MP3 file. s = open(file_name, 'rb').read() will put the whole file into a string object representing the raw bytes in your file (e.g. \xeb\xfe\x80). You can then search and edit the string, addressing the byte offsets with indeces using brackets: s[n]. Finally, just do a binary write of the MP3 frames you want in your new file(s), appending the ID3 header to the set of frames that you want to make up each file.

like image 44
Eric Avatar answered Oct 08 '22 16:10

Eric