#include <string>
#include <iostream>
extern "C"
{
#include "libavformat/avformat.h"
#include "libavcodec/avcodec.h"
};
using namespace std;
#pragma comment(lib,"avformat.lib")
#pragma comment(lib,"avcodec.lib")
int GetSampleIndex(int sample)
{
int index = 0;
switch (sample)
{
case 16000:index = 0x08; break;
case 44100:index = 0x04; break;
case 48000:index = 0x03; break;
case 8000:index = 0x0b; break;
}
return index;
}
int main()
{
AVFormatContext * pFormatCtx = nullptr;
std::string url = "rtmp://media3.sinovision.net:1935/live/livestream";
av_register_all();
if (avformat_open_input(&pFormatCtx, url.c_str(), nullptr, nullptr) < 0)
{
cout << "avformat_open_input failed." << endl;
return -1;
}
if (avformat_find_stream_info(pFormatCtx, nullptr) < 0)
{
cout << "avformat_find_stream_info failed." << endl;
return -1;
}
int audioindex = -1;
int sample = 0;
int channel = 0;
int profile = 0;
for (int i = 0; i < pFormatCtx->nb_streams; ++i)
{
if (pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
{
audioindex = i;
sample = pFormatCtx->streams[i]->codecpar->sample_rate;
channel = pFormatCtx->streams[i]->codecpar->channels;
profile = pFormatCtx->streams[i]->codecpar->profile;
break;
}
}
if (audioindex == -1)
{
cout << "audio index error." << endl;
return -1;
}
FILE* fp = fopen("1.aac", "wb");
if (fp == nullptr)
{
cout << "fopen failed." << endl;
return -1;
}
uint8_t padts[10];//
memset(padts, 0, 10);
int freqIdx = GetSampleIndex(sample);
padts[0] = (uint8_t)0xFF;
padts[1] = (uint8_t)0xF1;
padts[2] = (uint8_t)((profile << 6) + (freqIdx << 2) + (channel >> 2));
padts[6] = (uint8_t)0xFC;
AVPacket pkt;
int ret = -1;
for (;;)
{
if ((ret = av_read_frame(pFormatCtx, &pkt)) >= 0)
{
if (pkt.stream_index == audioindex)
{
padts[3] = (uint8_t)(((channel & 3) << 6) + ((7 + pkt.size) >> 11));// 增加ADTS头
padts[4] = (uint8_t)(((7 + pkt.size) >> 3) & 0xFF);
padts[5] = (uint8_t)((((7 + pkt.size) & 7) << 5) + 0x1F);
fwrite(padts, 7, 1, fp);
fwrite(pkt.data, 1, pkt.size, fp);//写数据到文件中
}
av_packet_unref(&pkt);
}
}
fclose(fp);
avformat_close_input(&pFormatCtx);
getchar();
return 0;
}
之前有点问题,谢谢反馈!现在正常了。采样率没有罗列那么多,需要的请自己按照AAC文档添加吧。
因篇幅问题不能全部显示,请点此查看更多更全内容