my_decode_audio.c

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <libavutil/frame.h> #include <libavutil/mem.h> #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #define AUDIO_INBUF_SIZE 20480 #define AUDIO_REFILL_THRESH 4096 int main(int argc, char **argv) { AVFormatContext* ctx_format = NULL; AVCodecContext* ctx_codec = NULL; AVCodec* codec = NULL; AVFrame* frame = av_frame_alloc(); int stream_idx; int ret; int i, ch; long data_size; FILE *outfile; outfile = fopen(argv[2], "wb"); const char* fin = argv[1]; AVStream *aud_stream = NULL; AVPacket* pkt = av_packet_alloc(); av_register_all(); if (ret = avformat_open_input(&ctx_format, fin, NULL, NULL) != 0) { printf("Couldn't open the file\n"); return ret; } if (avformat_find_stream_info(ctx_format, NULL) < 0) { printf("Couldn't find stream info\n"); return -1; // Couldn't find stream information } av_dump_format(ctx_format, 0, fin, 0); for (int i = 0; i < ctx_format->nb_streams; i++) if (ctx_format->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { stream_idx = i; aud_stream = ctx_format->streams[i]; break; } if (aud_stream == NULL) { printf("Couldn't find the Audio stream\n"); return -1; } codec = avcodec_find_decoder(aud_stream->codecpar->codec_id); if (!codec) { printf("codec not found\n"); exit(1); } ctx_codec = avcodec_alloc_context3(codec); if(avcodec_parameters_to_context(ctx_codec, aud_stream->codecpar)<0) printf("Error in codec param's\n"); if (avcodec_open2(ctx_codec, codec, NULL)<0) { printf("Couldn't open the codec\n"); return -1; } while(av_read_frame(ctx_format, pkt) >= 0) { int ret = avcodec_send_packet(ctx_codec, pkt); if (ret < 0 || ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) { printf("avcodec_send_packet: failed\n"); break; } ret = avcodec_receive_frame(ctx_codec, frame); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) { printf("error\n"); exit(0); } else if (ret < 0) { printf("Error during decoding\n"); exit(1); } data_size = av_get_bytes_per_sample(ctx_codec->sample_fmt); if (data_size < 0) { printf("Failed to calculate data size\n"); exit(1); } for (i = 0; i < frame->nb_samples; i++) for (ch = 0; ch < ctx_codec->channels; ch++) fwrite(frame->data[ch] + data_size*i, 1, data_size, outfile); av_packet_unref(pkt); } avformat_close_input(&ctx_format); av_packet_unref(pkt); avcodec_free_context(&ctx_codec); avformat_free_context(ctx_format); return 0; }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.