使用FFMPEG解码音频

时间:2011-05-22 11:42:53

标签: c++ audio ffmpeg decoding

我正在使用FFMPEG来解码音频文件,但我无法做到。

    AVFormatContext *pFormatCtx;
AVCodec *pCodec_audio;
AVCodecContext *aCodecCtx_audio = NULL;
AVPacket packet;
string outfilename = "salida.avi";
string filename = "john.wav";
int audioStream;
int out_size, len, size;
FILE *outfile;
int16_t *outbuf;
uint8_t inbuf[INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
avcodec_init();
/* register all the codecs */
av_register_all();

if(av_open_input_file(&pFormatCtx, filename.c_str(), NULL, 0, NULL) != 0) {
    cerr << "Archivo no encontrado" << endl;
    return -1; // Couldn't open file
}

if(av_find_stream_info(pFormatCtx) < 0) {
    cerr << " No encontro el stream de info" << endl;
    return -1;// Couldn't find stream information
}

dump_format(pFormatCtx, 0, filename.c_str(), 0);

for(unsigned int i=0; i < pFormatCtx->nb_streams; i++)
  if(pFormatCtx->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO)
      audioStream = i;
aCodecCtx_audio = pFormatCtx->streams[audioStream]->codec;
pCodec_audio = avcodec_find_decoder(aCodecCtx_audio->codec_id);
if(pCodec_audio == NULL) {
    cerr<< "Unsupported codec!" << endl;
    return -1; // Codec not found
}

if(avcodec_open(aCodecCtx_audio, pCodec_audio) < 0) {
    cerr << "No se pudo abrir el codec de audio" << endl;
    return -1;
}

outbuf = (int16_t*) av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);

outfile = fopen(outfilename.c_str(), "wb");
if (!outfile) {
    exit(1);
}

av_init_packet(&packet);
packet.data = inbuf;
while(av_read_frame(pFormatCtx, &packet) == 0) {
    if(packet.stream_index == audioStream) {
        size = packet.size;
        if (size == 0) {
            cerr << "Size = 0 " << endl;
            break;
        }
        while(size > 0) {
            out_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
            len = avcodec_decode_audio3(aCodecCtx_audio, outbuf, &out_size , &packet);
            //av_free_packet(&packet);
            cout << len << endl;
            if(len == -1) {
                cerr << "Error while decoding" << endl;
                return 1;
            }
            if(out_size > 0) {
                fwrite(outbuf, 1, out_size, outfile);
            }
            size -= len;
            packet.data += len;
        }
    }
}
av_free_packet(&packet);


fclose(outfile);
free(outbuf);
cout << "END CODE" << endl;
avcodec_close(aCodecCtx_audio);
av_free(aCodecCtx_audio);

在代码中我试图将.wav文件解码为.avi文件。输出文件(“salida.avi”)已创建,但无法播放。

0 个答案:

没有答案
相关问题