ffmpeg封装和解封装介绍-(3)解封装出数据并区分音频流视频流

源代码:


#include <iostream>
#include <thread>
using namespace std;
extern "C" { //指定函数是c语言函数,函数名不包含重载标注
//引用ffmpeg头文件
#include <libavformat/avformat.h>
}
//预处理指令导入库
#pragma comment(lib,"avformat.lib")
#pragma comment(lib,"avutil.lib")
#pragma comment(lib,"avcodec.lib")
void PrintErr(int err)
{
    char buf[1024] = { 0 };
    av_strerror(err, buf, sizeof(buf) - 1);
    cerr << buf << endl;
}
#define CERR(err) if(err!=0){ PrintErr(err);getchar();return -1;}

int main(int argc, char* argv[])
{
    //打开媒体文件
    const char* url = "v1080.mp4";

    //解封装输入上下文
    AVFormatContext* ic = nullptr;
    auto re = avformat_open_input(&ic, url,
        NULL,       //封装器格式 null 自动探测 根据后缀名或者文件头
        NULL        //参数设置,rtsp需要设置
    );
    CERR(re);

    //获取媒体信息 无头部格式
    re = avformat_find_stream_info(ic, NULL);
    CERR(re);

    //打印封装信息
    av_dump_format(ic, 0, url,
        0 //0表示上下文是输入 1 输出
    );
    AVStream* as = nullptr; //音频流
    AVStream* vs = nullptr; //视频流
    for (int i = 0; i < ic->nb_streams; i++)
    {
        //音频
        if (ic->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
        {
            as = ic->streams[i];
            cout << "=====音频=====" << endl;
            cout << "sample_rate:" << as->codecpar->sample_rate << endl;
        }
        else if (ic->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
        {
            vs = ic->streams[i];
            cout << "=========视频=========" << endl;
            cout << "width:" << vs->codecpar->width << endl;
            cout << "height:" << vs->codecpar->height << endl;
        }
    }


    AVPacket pkt;
    for (;;)
    {
        re = av_read_frame(ic, &pkt);
        CERR(re);
        if (vs && pkt.stream_index == vs->index)
        {
            cout << "视频:";
        }
        else if (as && pkt.stream_index == as->index)
        {
            cout << "音频:";
        }
        cout << pkt.pts << " : " << pkt.dts << " :" << pkt.size << endl;

        av_packet_unref(&pkt);
        //this_thread::sleep_for(100ms);
    }

    avformat_close_input(&ic);

    return 0;
}

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值