In this blog, we will learn how to cut a specific portion from an audio file (like MP3 or WAV) using C++ and the FFmpeg library. This is useful when you want to extract only a part of an audio track for example, from 10 seconds to 30 secondsĀ without re-encoding.
Cut particular portion on an audio file using C++
Requirements:
- FFmpeg installed (
sudo apt install libavformat-dev libavcodec-dev libavutil-dev
) - Basic knowledge of C++
- Audio file (like
input.mp3
)
Steps to Cut Audio in C++:
- Set Up FFmpeg in C++
extern "C" { #include <libavformat/avformat.h> #include <libavcodec/avcodec.h> #include <libavutil/time.h> }
- Open Input File
Useavformat_open_input()
to open the original audio file. - Find the Audio Stream
Detect the audio stream usingav_find_best_stream()
. - Seek to Start Time
Seek to the required starting point usingav_seek_frame()
. - Extract Packets in Duration Range
Loop through packets, check their timestamp, and write only those within the time range to the output file. - Save to Output File
Write selected audio data to a new file usingav_interleaved_write_frame()
.
Sample Command to Compile & Run:
Compile
g++ cut_audio.cpp -o cut_audio -lavformat -lavcodec -lavutil
Run
./cut_audio input.mp3 output.mp3 10 20
This will cut a
20-second portion
starting from the
10th second
.