Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Allocate and init re-usable frames
- audioFrameDecoded = av_frame_alloc();
- if (!audioFrameDecoded)
- die("Could not allocate audio frame");
- audioFrameDecoded->format = fileCodecContext->sample_fmt;
- audioFrameDecoded->channel_layout = fileCodecContext->channel_layout;
- audioFrameDecoded->channels = fileCodecContext->channels;
- audioFrameDecoded->sample_rate = fileCodecContext->sample_rate;
- audioFrameConverted = av_frame_alloc();
- if (!audioFrameConverted)
- die("Could not allocate audio frame");
- audioFrameConverted->nb_samples = audioCodecContext->frame_size;
- audioFrameConverted->format = audioCodecContext->sample_fmt;
- audioFrameConverted->channel_layout = audioCodecContext->channel_layout;
- audioFrameConverted->channels = audioCodecContext->channels;
- audioFrameConverted->sample_rate = audioCodecContext->sample_rate;
- AVPacket inPacket;
- av_init_packet(&inPacket);
- inPacket.data = NULL;
- inPacket.size = 0;
- int frameFinished = 0;
- while (av_read_frame(formatContext, &inPacket) >= 0) {
- if (inPacket.stream_index == streamId) {
- int len = avcodec_decode_audio4(fileCodecContext, audioFrameDecoded, &frameFinished, &inPacket);
- if (frameFinished) {
- // Convert
- uint8_t *convertedData=NULL;
- if (av_samples_alloc(&convertedData,
- NULL,
- audioCodecContext->channels,
- audioFrameConverted->nb_samples,
- audioCodecContext->sample_fmt, 0) < 0)
- die("Could not allocate samples");
- int outSamples = swr_convert(swrContext,
- &convertedData,
- audioFrameConverted->nb_samples,
- (const uint8_t **)audioFrameDecoded->data,
- audioFrameDecoded->nb_samples);
- if (outSamples < 0)
- die("Could not convert");
- size_t buffer_size = av_samples_get_buffer_size(NULL,
- audioCodecContext->channels,
- audioFrameConverted->nb_samples,
- audioCodecContext->sample_fmt,
- 0);
- if (buffer_size < 0)
- die("Invalid buffer size");
- if (avcodec_fill_audio_frame(audioFrameConverted,
- audioCodecContext->channels,
- audioCodecContext->sample_fmt,
- convertedData,
- buffer_size,
- 0) < 0)
- die("Could not fill frame");
- AVPacket outPacket;
- av_init_packet(&outPacket);
- outPacket.data = NULL;
- outPacket.size = 0;
- if (avcodec_encode_audio2(audioCodecContext, &outPacket, audioFrameConverted, &frameFinished) < 0)
- die("Error encoding audio frame");
- if (frameFinished) {
- outPacket.stream_index = audioStream->index;
- if (av_interleaved_write_frame(outContext, &outPacket) != 0)
- die("Error while writing audio frame");
- av_free_packet(&outPacket);
- }
- }
- }
- }
- av_frame_free(&audioFrameConverted);
- av_frame_free(&audioFrameDecoded);
- av_free_packet(&inPacket);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement