c++ - 在 Visual Studio 2010 上使用 FFMPEG 解码

标签 c++ visual-studio-2010 ffmpeg

我刚开始使用 FFMPEG 和 C++ 并尝试编写音频解码器,然后将解码后的音频写入文件。

但是我不确定要将哪些数据写入输出文件。据我所知,通过查看示例代码,它似乎是 AVFrame -> data[0]。 但是当我尝试在控制台上打印它时,我每次运行程序时都会得到一些不同的随机数。当我尝试将此 AVFrame->data[0] 写入文件时,我不断收到错误消息。

所以我的问题是如何在调用函数 av_codec_decode_audio4 后写入解码后的音频?

下面附上了我的代码,并传递了参数“C:\02.mp3”,这是我 PC 上有效 mp3 文件的路径。

感谢您的帮助。

// TestFFMPEG.cpp : Audio Decoder
//

#include "stdafx.h"

#include <iostream>
#include <fstream>
#include <sstream>

extern "C" {
    #include <avcodec.h>
    #include <avformat.h>
    #include <swscale.h>

}

using namespace std;


int main(int argc, char* argv[])
{
int audioStream = -1;

AVCodec         *aCodec;
AVPacket        avPkt;
AVFrame         *decode_frame = avcodec_alloc_frame();

AVCodecContext  *aCodecCtxt;
AVFormatContext *pFormatCtxt = NULL;

if(argc != 2) {     // Checking  whether there is enough argument
    return -1; 
}

av_register_all();  //Initialize CODEC
avformat_network_init();
av_init_packet (&avPkt);


 if (avformat_open_input (&pFormatCtxt, argv[1],NULL,NULL)!= 0 ){ //Opening File
     return -2;
 }

 if(avformat_find_stream_info (pFormatCtxt,NULL) < 0){ //Get Streams Info 
     return -3; 
 }

 AVStream *stream = NULL;
 //av_read_play (pFormatCtxt); //open streams


 for (int i = 0;  i < pFormatCtxt->nb_streams ; i++) { //Find Audio Stream
     if (pFormatCtxt->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO){
         audioStream =i;
     }
 }

 aCodecCtxt = pFormatCtxt ->streams [audioStream]->codec; // opening decoder   
 aCodec = avcodec_find_decoder( pFormatCtxt->streams [audioStream] ->codec->codec_id);

 if (!aCodec) {
     return -8;
 }

 if (avcodec_open2(aCodecCtxt,aCodec,NULL)!=0) {
     return -9; 
 } 

int cnt = 0;

while(av_read_frame(pFormatCtxt,&avPkt) >= 0 ){

    if (avPkt.stream_index == audioStream){
        int check = 0; 
        int result = avcodec_decode_audio4 (aCodecCtxt,decode_frame,&check, &avPkt);
        cout << "Decoded : "<< (int) decode_frame->data[0] <<", "<< "Check : " << check << ", Format :" << decode_frame->format <<" " << decode_frame->linesize[0]<< " "<<cnt <<endl;
    }
    av_free_packet(&avPkt);
    cnt++;
}


return aCodec ->id;  
} 

最佳答案

你做得对。

您解码的数据包含在指针 decode_frame->data[0]。以字节为单位的数据大小是decode_frame->linesize[0],音频样本的数量是decode_frame->nb_samples

因此,您可以将音频数据复制到您自己的缓冲区中,如下所示:

memcpy(OutputBuffer, decode_frame->data[0], decode_frame->linesize[0]);

关于c++ - 在 Visual Studio 2010 上使用 FFMPEG 解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16953444/

相关文章:

c++ - 提供一个基类的成员函数

visual-studio-2010 - 如何从项目中删除 Moles? (鼹鼠 0.94.51023.0/VS2010 SP1)

javascript - 在网站推送时压缩 .js 和 .css 文件

ffmpeg 从图像创建 gif,如何防止循环?

ffmpeg - 高清 FLV 视频播放缓慢

c++ - 错误 : Expression must have integral or unscoped enum type

C++、外部和 GCC

c# - 我如何使用像 C# 这样的 C++ 枚举类型?

c# - int++ 什么时候递增?

video - 在特定时间使用 FFMpeg drawtext 添加文本