An MP3 file is an audio file that uses a compression algorithm to reduce the overall file size. In this article, we will learn how to cut a particular portion of an MP3 file in Python.
Here we will first open the mp3 audio then slice the audio with Python code and save the result. Before we go forward, we need to install FFmpeg in your system as it is required to deal with mp3 files to download you can visit this site: https://phoenixnap.com/kb/ffmpeg-windows. Also, we will use pydub library to perform this task. we can install pydub using pip.
pip install pydub
Step 1: Open an mp3 file using pydub.
from pydub import AudioSegment
song = AudioSegment.from_mp3( "test.mp3" )
|
Step 2: Slice audio
# pydub does things in milliseconds ten_seconds = 10 * 1000
first_10_seconds = song[:ten_seconds]
last_5_seconds = song[ - 5000 :]
|
Step 3: Save the results as a new file in mp3 audio format.
first_10_seconds.export( "new.mp3" , format = "mp3" )
|
Example 1
Directory Structure before running code:
Here we will cut the first 10 seconds of the audio file.
from pydub import AudioSegment
# Open an mp3 file song = AudioSegment.from_file( "testing.mp3" ,
format = "mp3" )
# pydub does things in milliseconds ten_seconds = 10 * 1000
# song clip of 10 seconds from starting first_10_seconds = song[:ten_seconds]
# save file first_10_seconds.export( "first_10_seconds.mp3" ,
format = "mp3" )
print ( "New Audio file is created and saved" )
|
Output:
Directory Structure after running code:
Example 2
Directory Structure before running code:
Here we will cut the last 15 seconds of the audio file.
from pydub import AudioSegment
# Open an mp3 file song = AudioSegment.from_file( "testing.mp3" ,
format = "mp3" )
# pydub does things in milliseconds fifteen_seconds = 15 * 1000
# song clip of 10 seconds from starting first_10_seconds = song[ - fifteen_seconds : ]
# save file first_10_seconds.export( "last_15_seconds.mp3" , format = "mp3" )
print ( "New Audio file is created and saved" )
|
Output:
Directory Structure after running code.
Example 3:
Directory Structure before running code:
Here we will cut the mid portion of the audio file.
from pydub import AudioSegment
# Open an mp3 file song = AudioSegment.from_file( "testing.mp3" ,
format = "mp3" )
# start and end time start_min = 1
start_sec = 10
end_min = 2
end_sec = 5
# pydub does things in milliseconds, so convert time start = ((start_min * 60 ) + start_sec) * 1000
end = ((end_min * 60 ) + end_sec) * 1000
# song clip of 10 seconds from starting first_10_seconds = song[start: end]
# save file first_10_seconds.export( "Mid.mp3" , format = "mp3" )
print ( "New Audio file is created and saved" )
|
Output:
Directory Structure after running code.