ffmpeg rtsp音频流转成aac格式

#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文档添加吧。

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值