添加音频解码功能
一、前言
前面第四节“FFmpeg 从零开始开发简单的音视频播放器(四)”,进行了视频的解码和转码,我们这节就在该基础之上,添加音频解码功能。
二、代码
// FFmpegDll.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "FFmpegDll.h"
extern "C" {
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libswscale/swscale.h"
#include "libavutil/imgutils.h"
#include "libswresample/swresample.h"
}
AVFormatContext *fmt_ctx;
//流队列中,视频流所在的位置
int video_index = -1;
int audio_index = -1;
//解码上下文
AVCodecContext *video_codec_ctx;
AVCodecContext *audio_codec_ctx;
//输出缓存大小
int video_out_buffer_size;
int audio_out_buffer_size;
//输出缓存
uint8_t *video_out_buffer;
uint8_t *audio_out_buffer;
//转码后输出的视频帧(如yuv转rgb24)
AVFrame *video_out_frame = av_frame_alloc();
//格式转换上下文
struct SwsContext *video_convert_ctx;
struct SwrContext *audio_convert_ctx;
//解码前数据包
AVPacket *packet = (AVPacket *)malloc(sizeof(AVPacket));
//音频声道数量
int nb_channels;
enum AVSampleFormat out_sample_fmt = AV_SAMPLE_FMT_S16;//输出的采样格式 16bit PCM
int sample_rate;//采样率
uint64_t out_ch_layout = AV_CH_LAYOUT_STEREO;//输出的声道布局:立体声
//初始化FFmpeg
//@param *url 媒体地址(本地/网络地址)
int init_ffmpeg(char *url) {
av_register_all();//注册组件
avformat_network_init();//支持网络流
fmt_ctx = avformat_alloc_context();
//打开文件
if (avformat_open_input(&fmt_ctx, url, NULL, NULL) != 0) {
return -1;
}
//查找流信息
if (avformat_find_stream_info(fmt_ctx, NULL) < 0)
{
return -1;
}
//找到流队列中,视频流所在位置
for (int i = 0; i < fmt_ctx->nb_streams; i++) {
if