Trim part of an Mp3 file in C++

extern “C” {
#include <libavformat/avformat.h>
}

void trimMp3(const char* input, const char* output, int start, int duration) {
av_register_all();
AVFormatContext *inCtx = nullptr, *outCtx = nullptr;
avformat_open_input(&inCtx, input, nullptr, nullptr);
avformat_find_stream_info(inCtx, nullptr);
avformat_alloc_output_context2(&outCtx, nullptr, nullptr, output);

int audioIndex = av_find_best_stream(inCtx, AVMEDIA_TYPE_AUDIO, -1, -1, nullptr, 0);
AVStream *inStream = inCtx->streams[audioIndex];
AVStream *outStream = avformat_new_stream(outCtx, nullptr);
avcodec_parameters_copy(outStream->codecpar, inStream->codecpar);
avio_open(&outCtx->pb, output, AVIO_FLAG_WRITE);
avformat_write_header(outCtx, nullptr);

int64_t startPts = av_rescale_q(start, AV_TIME_BASE_Q, inStream->time_base);
int64_t endPts = av_rescale_q(start + duration, AV_TIME_BASE_Q, inStream->time_base);
av_seek_frame(inCtx, audioIndex, startPts, AVSEEK_FLAG_ANY);

AVPacket pkt;
while (av_read_frame(inCtx, &pkt) >= 0) {
if (pkt.stream_index == audioIndex && pkt.pts >= startPts && pkt.pts <= endPts) {
pkt.pts = av_rescale_q(pkt.pts, inStream->time_base, outStream->time_base);
pkt.dts = pkt.pts;
av_interleaved_write_frame(outCtx, &pkt);
}
av_packet_unref(&pkt);
}
av_write_trailer(outCtx);
avio_closep(&outCtx->pb);
avformat_close_input(&inCtx);
avformat_free_context(outCtx);
}

int main(int argc, char* argv[]) {
if (argc < 5) {
fprintf(stderr, “Usage: %s <input> <output> <start> <duration>\n”, argv[0]);
return -1;
}
trimMp3(argv[1], argv[2], atoi(argv[3]), atoi(argv[4]));
return 0;
}

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top