<div>
<p>I use following code snippet to decode audio files (tested with MP3,WAV,WMV).</p>
<p>But when it plays the audio , it just gives static sounds and crashes time to time. Any hints on what i am doing wrong here ?</p></div>
<div> </div>
<div>-----------------------------------------------------------------------------------------------------</div>
<div> </div>
<div>#include <stdlib.h><br>#include <stdio.h><br>#include <string.h><br>#include <math.h></div>
<p><br>extern "C" {<br>#include "libavutil/mathematics.h"<br>#include "libavformat/avformat.h"<br>#include "libswscale/swscale.h"<br>#include <ao/ao.h></p>
<p>}</p>
<p>void die(const char *msg)<br>{<br> fprintf(stderr,"%s\n",msg);<br> exit(1);<br>}</p>
<p>int main(int argc, char **argv)<br>{</p>
<p> const char* input_filename=argv[1];</p>
<p> //avcodec_register_all();<br> av_register_all();<br> //av_ini</p>
<p> AVFormatContext* container=avformat_alloc_context();<br> if(avformat_open_input(&container,input_filename,NULL,NULL)<0){<br>  die("Could not open file");<br> }</p>
<p> if(av_find_stream_info(container)<0){<br>  die("Could not find file info");<br> }<br> av_dump_format(container,0,input_filename,false);</p>
<p> int stream_id=-1;<br> int i;<br> for(i=0;i<container->nb_streams;i++){<br>  if(container->streams[i]->codec->codec_type==AVMEDIA_TYPE_AUDIO){<br>   stream_id=i;<br>   break;<br>  }<br> }<br> if(stream_id==-1){<br>
  die("Could not find Audio Stream");<br> }</p>
<p> AVDictionary *metadata=container->metadata;</p>
<p> AVCodecContext *ctx=container->streams[stream_id]->codec;<br> AVCodec *codec=avcodec_find_decoder(ctx->codec_id);</p>
<p> if(codec==NULL){<br>  die("cannot find codec!");<br> }</p>
<p> if(avcodec_open(ctx,codec)<0){<br>  die("Codec cannot be found");<br> }</p>
<p> //ctx=avcodec_alloc_context3(codec);</p>
<p> //initialize AO lib<br> ao_initialize();</p>
<p> int driver=ao_default_driver_id();</p>
<p> ao_sample_format sformat;<br> sformat.bits=16;<br> sformat.channels=2;<br> sformat.rate=44100;<br> sformat.byte_format=AO_FMT_NATIVE;<br> sformat.matrix=0;</p>
<p> ao_device *adevice=ao_open_live(driver,&sformat,NULL);<br> //end of init AO LIB</p>
<p> AVPacket packet;<br> av_init_packet(&packet);</p>
<p> AVFrame *frame=avcodec_alloc_frame();</p>
<p> int buffer_size=AVCODEC_MAX_AUDIO_FRAME_SIZE;<br> uint8_t buffer[buffer_size];<br> packet.data=buffer;<br> packet.size =buffer_size;</p>
<p> </p>
<p> int len;<br> int frameFinished=0;<br> while(av_read_frame(container,&packet)>=0)<br> {</p>
<p>  if(packet.stream_index==stream_id){<br>   //printf("Audio Frame read  \n");<br>   int len=avcodec_decode_audio4(ctx,frame,&frameFinished,&packet);<br>   //frame-><br>   if(frameFinished){<br>    //printf("Finished reading Frame %d %d\n",packet.size,len);<br>
    ao_play(adevice, (char*)frame->data, len);<br>   }</p>
<p>  }</p>
<p><br> }</p>
<p> av_close_input_file(container);<br> ao_shutdown();<br> return 0;<br>}<br></p>