2013-10-20 53 views
0

我使用下面的代码(从libavcodec的给出的实施例修改的)来解码音频文件解码M4A和倾倒PCM数据还给噪声

int main(int argc, char **argv) 
{ 
    av_register_all(); 
    avcodec_register_all(); 

    char *filename = argv[1]; 
    char *outfilename = argv[2]; 

    FILE *outfile; 

    AVCodec *codec; 
    AVCodecContext *c= NULL; 
    AVPacket avpkt; 
    AVFrame *frame = av_frame_alloc(); 

    printf("Decode audio file %s to %s\n", filename, outfilename); 

    outfile = fopen(outfilename, "wb"); 
    if (!outfile) { 
     fprintf(stderr, "Could not write to %s\n", outfilename); 
     av_free(c); 
     exit(1); 
    } 

    AVFormatContext *format_context = NULL; 
    avformat_open_input(&format_context, filename, NULL, NULL); 
    printf("Opened format input\n"); 

    int find_result = avformat_find_stream_info(format_context, NULL); 
    if (find_result < 0) { 
     fprintf(stderr, "Cannot find stream info\n"); 
     avformat_close_input(&format_context); 
     exit(-1); 
    } 

    int audio_stream_idx = av_find_best_stream(format_context, AVMEDIA_TYPE_AUDIO, -1, -1, &codec, 0); 

    if (audio_stream_idx < 0) { 
     fprintf(stderr,"Couldn't find stream information\n"); 
     exit(-1); 
    } 

    // Get a pointer to the codec context for the audio stream 
    c = format_context->streams[audio_stream_idx]->codec; 
    av_opt_set_int(c, "refcounted_frames", 1, 0); 

    if (avcodec_open2(c, codec, NULL) < 0) { 
     fprintf(stderr, "Could not open codec\n"); 
     exit(-1); 
    } 

    // read the audio frames 
    int ret, got_frame; 
    while (1) { 
     if ((ret = av_read_frame(format_context, &avpkt)) < 0) 
      break; 
     if (avpkt.stream_index == audio_stream_idx) { 
      avcodec_get_frame_defaults(frame); 
      got_frame = 0; 
      ret = avcodec_decode_audio4(c, frame, &got_frame, &avpkt); 
      if (ret < 0) { 
       fprintf(stderr, "Error decoding audio\n"); 
       continue; 
      } 

      if (got_frame) { 
       // write to disk 
       fwrite(frame->extended_data[0], 1, frame->linesize[0], outfile); 
      } 
     } 
     av_free_packet(&avpkt); 
    } 

    fclose(outfile); 

    printf("Finished\n"); 
    if (c) 
     avcodec_close(c); 
    avformat_close_input(&format_context); 
    av_frame_free(&frame); 
} 

我试图.mp3.m4a文件; .mp3文件正常工作,但不适用于.m4a文件。任何帮助?

+0

首先要检查一个显而易见的事情 - 您使用的FFmpeg构建包含所需的MPEG-4解析器和AAC解码器。 –

+0

@RomanR。是的,它确实建立。我改进了我的代码,现在它可以正确输出一个通道;然而其他频道仍然是静态噪音.. – lynnard

+0

@lynnard。我遇到了同样的问题,仍然在挣扎。能够播放mp3音频,但不是aac。我用所有的编解码器和解析器重建了ffmpeg,但仍然没有成功。你或任何机构是否找到了解决方案? –

回答

2

大多数aac文件处于FLOAT格式,即AV_SAMPLE_FMT_FLTP,而诸如libao的库仅能够以整数格式播放音频,即AV_SAMPLE_FORMAT_S16

因此,您需要使用libavresample对音乐进行重新采样并根据需要转换格式。