Decode an audio stream using libavcodec and play through libAO .

FFMPEG is an awesome set of libraries for decoding/encoding audio and video.Since its a highly experimental  and keep updating
regulary , I found that many of the samples that I can find on the net are kind of outdated.
Following code snippet shows ,how to decode an audio stream using libavcodec and play it using crossplatform audio library – libAO .


[sourcecode language=”python” wraplines=”false” collapse=”false”]
your source code goes here
[/sourcecode]

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>

extern “C” {
#include “libavutil/mathematics.h”
#include “libavformat/avformat.h”
#include “libswscale/swscale.h”
#include <ao/ao.h>

}

void die(const char *msg)
{
fprintf(stderr,”%s\n”,msg);
exit(1);
}

int main(int argc, char **argv)
{

const char* input_filename=argv[1]

av_register_all();

AVFormatContext* container=avformat_alloc_context();
if(avformat_open_input(&container,input_filename,NULL,NULL)<0){
die(“Could not open file”);
}

if(av_find_stream_info(container)<0){
die(“Could not find file info”);
}

av_dump_format(container,0,input_filename,false);

int stream_id=-1;
int i;
for(i=0;i<container->nb_streams;i++){
if(container->streams[i]->codec->codec_type==AVMEDIA_TYPE_AUDIO){
stream_id=i;
break;
}
}
if(stream_id==-1){
die(“Could not find Audio Stream”);
}

AVCodecContext *ctx=container->streams[stream_id]->codec;
AVCodec *codec=avcodec_find_decoder(ctx->codec_id);

if(codec==NULL){
die(“cannot find codec!”);
}

if(avcodec_open(ctx,codec)<0){
die(“Codec cannot be opended!”);
}

//initialize AO lib
ao_initialize();

int driver=ao_default_driver_id();

ao_sample_format sformat;
AVSampleFormat sfmt=ctx->sample_fmt;
//assign device sample rate depend on the input stream
if(sfmt==AV_SAMPLE_FMT_U8){
sformat.bits=8;
}else if(sfmt==AV_SAMPLE_FMT_S16){
sformat.bits=16;
}else if(sfmt==AV_SAMPLE_FMT_S32){
sformat.bits=32;
}

sformat.channels=ctx->channels;
sformat.rate=ctx->sample_rate;
sformat.byte_format=AO_FMT_NATIVE;
sformat.matrix=0;

ao_device *adevice=ao_open_live(driver,&sformat,NULL);
//end of init AO LIB

//data packet read from the stream
AVPacket packet;
av_init_packet(&packet);

int buffer_size=AVCODEC_MAX_AUDIO_FRAME_SIZE+ FF_INPUT_BUFFER_PADDING_SIZE;;
uint8_t buffer[buffer_size];
packet.data=buffer;
packet.size =buffer_size;

//frame ,where the decoded data will be written
AVFrame *frame=avcodec_alloc_frame();

int len;
int frameFinished=0;
while(av_read_frame(container,&packet)>=0)
{

if(packet.stream_index==stream_id){
int len=avcodec_decode_audio4(ctx,frame,&frameFinished,&packet);

if(frameFinished){
//play the decoded bytes
ao_play(adevice, (char*)frame->extended_data[0],frame->linesize[0] );
}else{
//
}

}else {
//someother stream,probably a video stream
}

}

av_close_input_file(container);
ao_shutdown();
return 0;
}