Cut a MP3 file in Python
Last Updated :
23 Jan, 2023
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.
Python3
from pydub import AudioSegment
song = AudioSegment.from_mp3( "test.mp3" )
|
Step 2: Slice audio
Python3
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.
Python3
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.
Python3
from pydub import AudioSegment
song = AudioSegment.from_file( "testing.mp3" ,
format = "mp3" )
ten_seconds = 10 * 1000
first_10_seconds = song[:ten_seconds]
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.
Python3
from pydub import AudioSegment
song = AudioSegment.from_file( "testing.mp3" ,
format = "mp3" )
fifteen_seconds = 15 * 1000
first_10_seconds = song[ - fifteen_seconds : ]
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.
Python3
from pydub import AudioSegment
song = AudioSegment.from_file( "testing.mp3" ,
format = "mp3" )
start_min = 1
start_sec = 10
end_min = 2
end_sec = 5
start = ((start_min * 60 ) + start_sec) * 1000
end = ((end_min * 60 ) + end_sec) * 1000
first_10_seconds = song[start: end]
first_10_seconds.export( "Mid.mp3" , format = "mp3" )
print ( "New Audio file is created and saved" )
|
Output:
Directory Structure after running code.
Share your thoughts in the comments
Please Login to comment...