其实这篇的内容和(一)用ffmpeg解码视频基本是一样的,重点还是给ffmpeg指定callback函数,而这个函数是从RTSP服务端那里获取音频数据的。

这里,解码音频的示例代码量之所以比解码视频的略微复杂,主要是因为ffmpeg解码音频时要比解码视频要复杂一点,具体可以参见ffmpeg解码音频示例以及官网示例代码

具体内容将不再赘述,源码如下:

 extern "C"
{
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavformat/avio.h>
#include <libswscale/swscale.h>
#include <libswresample/swresample.h>
} #include <SDL.h>
#include <SDL_thread.h> #ifdef __MINGW32__
#undef main /* Prevents SDL from overriding main() */
#endif #include <stdio.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h> // compatibility with newer API
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55,28,1)
#define av_frame_alloc avcodec_alloc_frame
#define av_frame_free avcodec_free_frame
#endif #define SDL_AUDIO_BUFFER_SIZE 1024
#define MAX_AUDIO_FRAME_SIZE 192000 #include <signal.h>
#include "rtspClient.h"
#include <iostream>
#include <string> using std::cout;
using std::endl; int rtspClientRequest(RtspClient * Client, string url);
int fill_iobuffer(void * opaque, uint8_t * buf, int bufsize); typedef struct AudioParams {
int freq;
int channels;
int64_t channel_layout;
enum AVSampleFormat fmt;
int frame_size;
int bytes_per_sec;
} AudioParams;
int sample_rate, nb_channels;
int64_t channel_layout;
AudioParams audio_hw_params_tgt;
AudioParams audio_hw_params_src; int resample(AVFrame * af, uint8_t * audio_buf, int * audio_buf_size); struct SwrContext * swr_ctx = NULL; int resample(AVFrame * af, uint8_t * audio_buf, int * audio_buf_size)
{
int data_size = ;
int resampled_data_size = ;
int64_t dec_channel_layout;
data_size = av_samples_get_buffer_size(NULL,
av_frame_get_channels(af),
af->nb_samples,
(AVSampleFormat)af->format,
); dec_channel_layout =
(af->channel_layout && av_frame_get_channels(af) == av_get_channel_layout_nb_channels(af->channel_layout)) ?
af->channel_layout : av_get_default_channel_layout(av_frame_get_channels(af));
if( af->format != audio_hw_params_src.fmt ||
af->sample_rate != audio_hw_params_src.freq ||
dec_channel_layout != audio_hw_params_src.channel_layout ||
!swr_ctx) {
swr_free(&swr_ctx);
swr_ctx = swr_alloc_set_opts(NULL,
audio_hw_params_tgt.channel_layout, (AVSampleFormat)audio_hw_params_tgt.fmt, audio_hw_params_tgt.freq,
dec_channel_layout, (AVSampleFormat)af->format, af->sample_rate,
, NULL);
if (!swr_ctx || swr_init(swr_ctx) < ) {
av_log(NULL, AV_LOG_ERROR,
"Cannot create sample rate converter for conversion of %d Hz %s %d channels to %d Hz %s %d channels!\n",
af->sample_rate, av_get_sample_fmt_name((AVSampleFormat)af->format), av_frame_get_channels(af),
audio_hw_params_tgt.freq, av_get_sample_fmt_name(audio_hw_params_tgt.fmt), audio_hw_params_tgt.channels);
swr_free(&swr_ctx);
return -;
}
printf("swr_init\n");
audio_hw_params_src.channels = av_frame_get_channels(af);
audio_hw_params_src.fmt = (AVSampleFormat)af->format;
audio_hw_params_src.freq = af->sample_rate;
} if (swr_ctx) {
const uint8_t **in = (const uint8_t **)af->extended_data;
uint8_t **out = &audio_buf;
int out_count = (int64_t)af->nb_samples * audio_hw_params_tgt.freq / af->sample_rate + ;
int out_size = av_samples_get_buffer_size(NULL, audio_hw_params_tgt.channels, out_count, audio_hw_params_tgt.fmt, );
int len2;
if (out_size < ) {
av_log(NULL, AV_LOG_ERROR, "av_samples_get_buffer_size() failed\n");
return -;
}
av_fast_malloc(&audio_buf, (unsigned int*)audio_buf_size, out_size);
if (!audio_buf)
return AVERROR(ENOMEM);
len2 = swr_convert(swr_ctx, out, out_count, in, af->nb_samples);
if (len2 < ) {
av_log(NULL, AV_LOG_ERROR, "swr_convert() failed\n");
return -;
}
if (len2 == out_count) {
av_log(NULL, AV_LOG_WARNING, "audio buffer is probably too small\n");
if (swr_init(swr_ctx) < )
swr_free(&swr_ctx);
}
resampled_data_size = len2 * audio_hw_params_tgt.channels * av_get_bytes_per_sample(audio_hw_params_tgt.fmt);
} else {
audio_buf = af->data[];
resampled_data_size = data_size;
} return resampled_data_size;
} static void sigterm_handler(int sig)
{
exit();
} typedef struct PacketQueue {
AVPacketList *first_pkt, *last_pkt;
int nb_packets;
int size;
SDL_mutex *mutex;
SDL_cond *cond;
} PacketQueue; PacketQueue audioq; int quit = ; void packet_queue_init(PacketQueue *q) {
memset(q, , sizeof(PacketQueue));
q->mutex = SDL_CreateMutex();
q->cond = SDL_CreateCond();
} int packet_queue_put(PacketQueue *q, AVPacket *pkt) { AVPacketList *pkt1;
if(av_dup_packet(pkt) < ) {
return -;
}
pkt1 = (AVPacketList *)av_malloc(sizeof(AVPacketList));
if (!pkt1)
return -;
pkt1->pkt = *pkt;
pkt1->next = NULL; SDL_LockMutex(q->mutex); if (!q->last_pkt)
q->first_pkt = pkt1;
else
q->last_pkt->next = pkt1;
q->last_pkt = pkt1;
q->nb_packets++;
q->size += pkt1->pkt.size;
SDL_CondSignal(q->cond); SDL_UnlockMutex(q->mutex);
return ;
} int packet_queue_put_nullpacket(PacketQueue *q, int stream_index)
{
AVPacket pkt1, *pkt = &pkt1;
av_init_packet(pkt);
pkt->data = NULL;
pkt->size = ;
pkt->stream_index = stream_index;
return packet_queue_put(q, pkt);
} static int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block)
{
AVPacketList *pkt1;
int ret; SDL_LockMutex(q->mutex); for(;;) { if(quit) {
ret = -;
break;
} pkt1 = q->first_pkt;
if (pkt1) {
q->first_pkt = pkt1->next;
if (!q->first_pkt)
q->last_pkt = NULL;
q->nb_packets--;
q->size -= pkt1->pkt.size;
*pkt = pkt1->pkt;
av_free(pkt1);
ret = ;
break;
} else if (!block) {
ret = ;
break;
} else {
SDL_CondWait(q->cond, q->mutex);
}
}
SDL_UnlockMutex(q->mutex);
return ret;
} AVFrame frame;
int audio_decode_frame(AVCodecContext *aCodecCtx, uint8_t *audio_buf, int buf_size) { static AVPacket pkt;
static uint8_t *audio_pkt_data = NULL;
static int audio_pkt_size = ; int len1, data_size = ; for(;;) {
while(audio_pkt_size > ) {
int got_frame = ;
len1 = avcodec_decode_audio4(aCodecCtx, &frame, &got_frame, &pkt);
if(len1 < ) {
/* if error, skip frame */
audio_pkt_size = ;
break;
}
audio_pkt_data += len1;
audio_pkt_size -= len1;
data_size = ;
if(got_frame) {
data_size = resample(&frame, audio_buf, &buf_size);
// data_size = av_samples_get_buffer_size(NULL,
// aCodecCtx->channels,
// frame.nb_samples,
// aCodecCtx->sample_fmt,
// 1);
assert(data_size <= buf_size);
// memcpy(audio_buf, frame.data[0], data_size);
}
if(data_size <= ) {
/* No data yet, get more frames */
continue;
}
// memcpy(audio_buf, frame.data[0], data_size); /* We have data, return it and come back for more later */
return data_size;
}
if(pkt.data)
av_free_packet(&pkt); if(quit) {
return -;
} if(packet_queue_get(&audioq, &pkt, ) < ) {
return -;
}
audio_pkt_data = pkt.data;
audio_pkt_size = pkt.size;
}
} void audio_callback(void *userdata, Uint8 *stream, int len) { AVCodecContext *aCodecCtx = (AVCodecContext *)userdata;
int len1, audio_size; static uint8_t audio_buf[(MAX_AUDIO_FRAME_SIZE * ) / ];
static unsigned int audio_buf_size = ;
static unsigned int audio_buf_index = ; while(len > ) {
if(audio_buf_index >= audio_buf_size) {
/* We have already sent all our data; get more */
audio_size = audio_decode_frame(aCodecCtx, audio_buf, sizeof(audio_buf));
if(audio_size < ) {
/* If error, output silence */
audio_buf_size = ; // arbitrary?
memset(audio_buf, , audio_buf_size);
} else {
audio_buf_size = audio_size;
}
audio_buf_index = ;
}
len1 = audio_buf_size - audio_buf_index;
if(len1 > len)
len1 = len;
memcpy(stream, (uint8_t *)audio_buf + audio_buf_index, len1);
len -= len1;
stream += len1;
audio_buf_index += len1;
}
} int main(int argc, char *argv[]) { AVFormatContext *pFormatCtx = NULL;
int i, audioStream;
AVPacket packet; AVCodecContext *aCodecCtxOrig = NULL;
AVCodecContext *aCodecCtx = NULL;
AVCodec *aCodec = NULL; SDL_Event event;
SDL_AudioSpec wanted_spec, spec; AVInputFormat *piFmt = NULL;
RtspClient Client; signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */ if(argc != ) {
cout << "Usage: " << argv[] << " <URL>" << endl;
cout << "For example: " << endl;
cout << argv[] << " rtsp://127.0.0.1/ansersion" << endl;
return ;
}
rtspClientRequest(&Client, argv[]);
// Register all formats and codecs
av_register_all(); if(SDL_Init(SDL_INIT_AUDIO)) {
fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
exit();
} // // Open video file
// if(avformat_open_input(&pFormatCtx, argv[1], NULL, NULL)!=0)
// return -1; // Couldn't open file pFormatCtx = NULL;
pFormatCtx = avformat_alloc_context();
unsigned char * iobuffer = (unsigned char *)av_malloc();
AVIOContext * avio = avio_alloc_context(iobuffer, , , &Client, fill_iobuffer, NULL, NULL);
pFormatCtx->pb = avio; if(!avio) {
printf("avio_alloc_context error!!!\n");
return -;
} if(av_probe_input_buffer(avio, &piFmt, "", NULL, , ) < ) {
printf("av_probe_input_buffer error!\n");
return -;
} else {
printf("probe success\n");
printf("format: %s[%s]\n", piFmt->name, piFmt->long_name);
} int err = avformat_open_input(&pFormatCtx, "nothing", NULL, NULL);
if(err) {
printf("avformat_open_input error: %d\n", err);
return -;
}
// Retrieve stream information
if(avformat_find_stream_info(pFormatCtx, NULL)<)
return -; // Couldn't find stream information // Dump information about file onto standard error
// av_dump_format(pFormatCtx, 0, argv[1], 0);
av_dump_format(pFormatCtx, , "", ); // Find the first video stream
audioStream=-;
for(i=; i<pFormatCtx->nb_streams; i++) {
if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_AUDIO &&
audioStream < ) {
audioStream=i;
}
}
// if(videoStream==-1)
// return -1; // Didn't find a video stream
if(audioStream==-)
return -; aCodecCtxOrig=pFormatCtx->streams[audioStream]->codec;
aCodec = avcodec_find_decoder(aCodecCtxOrig->codec_id);
if(!aCodec) {
fprintf(stderr, "Unsupported codec!\n");
return -;
} // Copy context
aCodecCtx = avcodec_alloc_context3(aCodec);
if(avcodec_copy_context(aCodecCtx, aCodecCtxOrig) != ) {
fprintf(stderr, "Couldn't copy codec context");
return -; // Error copying codec context
} avcodec_open2(aCodecCtx, aCodec, NULL); sample_rate = aCodecCtx->sample_rate;
nb_channels = aCodecCtx->channels;
channel_layout = aCodecCtx->channel_layout; // printf("channel_layout=%" PRId64 "\n", channel_layout);
printf("channel_layout=%lld\n", channel_layout);
printf("nb_channels=%d\n", nb_channels);
printf("freq=%d\n", sample_rate); if (!channel_layout || nb_channels != av_get_channel_layout_nb_channels(channel_layout)) {
channel_layout = av_get_default_channel_layout(nb_channels);
channel_layout &= ~AV_CH_LAYOUT_STEREO_DOWNMIX;
printf("correction\n");
} // Set audio settings from codec info
wanted_spec.freq = sample_rate;
wanted_spec.format = AUDIO_S16SYS;
wanted_spec.channels = nb_channels;
wanted_spec.silence = ;
wanted_spec.samples = SDL_AUDIO_BUFFER_SIZE;
wanted_spec.callback = audio_callback;
wanted_spec.userdata = aCodecCtx; if(SDL_OpenAudio(&wanted_spec, &spec) < ) {
fprintf(stderr, "SDL_OpenAudio: %s\n", SDL_GetError());
return -;
}
printf("freq: %d\tchannels: %d\n", spec.freq, spec.channels); audio_hw_params_tgt.fmt = AV_SAMPLE_FMT_S16;
audio_hw_params_tgt.freq = spec.freq;
audio_hw_params_tgt.channel_layout = channel_layout;
audio_hw_params_tgt.channels = spec.channels;
audio_hw_params_tgt.frame_size = av_samples_get_buffer_size(NULL, audio_hw_params_tgt.channels, , audio_hw_params_tgt.fmt, );
audio_hw_params_tgt.bytes_per_sec = av_samples_get_buffer_size(NULL, audio_hw_params_tgt.channels, audio_hw_params_tgt.freq, audio_hw_params_tgt.fmt, );
if (audio_hw_params_tgt.bytes_per_sec <= || audio_hw_params_tgt.frame_size <= ) {
printf("size error\n");
return -;
}
audio_hw_params_src = audio_hw_params_tgt; // audio_st = pFormatCtx->streams[index]
packet_queue_init(&audioq);
SDL_PauseAudio(); // Read frames and save first five frames to disk
i=;
int ret = ;
// while(av_read_frame(pFormatCtx, &packet)>=0) {
while(ret >= ) {
ret = av_read_frame(pFormatCtx, &packet); if(ret < ) {
/* av_read_frame may get error when RTP data are blocked due to the network busy */
if(ret == AVERROR_EOF || avio_feof(pFormatCtx->pb)) {
packet_queue_put_nullpacket(&audioq, audioStream);
printf("continue ret=%d\n", ret);
ret = ;
continue;
}
printf("ret=%d\n", ret);
break;
}
printf("av_read_frame\n");
if(packet.stream_index==audioStream) {
packet_queue_put(&audioq, &packet);
} else {
av_free_packet(&packet);
}
// Free the packet that was allocated by av_read_frame
SDL_PollEvent(&event);
switch(event.type) {
case SDL_QUIT:
printf("SDL_QUIT\n");
quit = ;
SDL_Quit();
exit();
break;
default:
printf("SDL_Default\n");
break;
} } while() SDL_Delay(); // Close the codecs
avcodec_close(aCodecCtxOrig);
avcodec_close(aCodecCtx); // Close the video file
avformat_close_input(&pFormatCtx); return ;
} int rtspClientRequest(RtspClient * Client, string url)
{
if(!Client) return -; // cout << "Start play " << url << endl;
string RtspUri(url);
// string RtspUri("rtsp://192.168.81.145/ansersion"); /* Set up rtsp server resource URI */
Client->SetURI(RtspUri); /* Send DESCRIBE command to server */
Client->DoDESCRIBE(); /* Parse SDP message after sending DESCRIBE command */
Client->ParseSDP(); /* Send SETUP command to set up all 'audio' and 'video'
* sessions which SDP refers. */
Client->DoSETUP(); /* Send PLAY command to play only 'video' sessions.*/
Client->DoPLAY("audio"); return ;
} int fill_iobuffer(void * opaque, uint8_t * buf, int bufsize) {
size_t size = ;
if(!opaque) return -;
RtspClient * Client = (RtspClient *)opaque;
if(!Client->GetMediaData("audio", buf, &size, bufsize)) size = ;
printf("fill_iobuffer size: %u\n", size);
return size;
}

注:

1, 兼容myRtspClient-1.2.1及以上版本,且仅支持接收mp2,mp3音频;

2, 音频解码原理可参见:http://www.cnblogs.com/ansersion/p/5265033.html;

3, 示例源码编译需要SDL和ffmpeg,具体可参见解码视频的附录二;

4, 博主编译环境为 x86_64位ubuntu 16.04,以供参考。

myRtspClient-1.2.3

ffmpeg-2.8.5

下载源码以及Makefile

编译、配置和运行同上一篇:用ffmpeg解码视频

上一篇               回目录            下一篇

一个基于JRTPLIB的轻量级RTSP客户端(myRTSPClient)——解码篇:(二)用ffmpeg解码音频的更多相关文章

  1. 一个基于JRTPLIB的轻量级RTSP客户端(myRTSPClient)——实现篇:(四)用户接口层之处理SDP报文

    当RTSP客户端向RTSP服务端发送DESCRIBE命令时,服务端理应当回复一条SDP报文. 该SDP报文中包含RTSP服务端的基本信息.所能提供的音视频媒体类型以及相应的负载能力,以下是一段SDP示 ...

  2. 一个基于JRTPLIB的轻量级RTSP客户端(myRTSPClient)——实现篇:(五)用户接口层之提取媒体流数据

    当RTSP客户端向RTSP服务端发送完PLAY命令后,RTSP服务端就会另外开启UDP端口(SDP协商定义的端口)发送RTP媒体流数据包.这些数据包之间会间隔一段时间(毫秒级)陆续被发送到RTSP客户 ...

  3. 一个基于JRTPLIB的轻量级RTSP客户端(myRTSPClient)——实现篇:(十)使用JRTPLIB传输RTP数据

    myRtspClient通过简单修改JRTPLIB的官方例程作为其RTP传输层实现.因为JRTPLIB使用的是CMAKE编译工具,这就是为什么编译myRtspClient时需要预装CMAKE. 该部分 ...

  4. 一个基于JRTPLIB的轻量级RTSP客户端(myRTSPClient)——实现篇:(二)用户接口层之RtspClient类及其构造函数

    RtspClient类是myRTSPClient函数库所有特性集中实现的地方. 主要为用户提供: 1. RTSP协议通信接口函数,如DoOPTIONS(): 2. RTSP账号.密码设置函数,如Set ...

  5. 一个基于JRTPLIB的轻量级RTSP客户端(myRTSPClient)——实现篇:(一)概览

    myRTSPClient主要可以分成3个部分: 1. RTSPClient用户接口层: 2. RTP 音视频传输解析层: 3. RTP传输层. "RTSPClient用户接口层": ...

  6. 一个基于JRTPLIB的轻量级RTSP客户端(myRTSPClient)——实现篇:(三)用户接口层之RTSP命令

    截至版本1.2.3,myRtspClient函数库共支持以下6个RTSP命令: (1)OPTIONS (2)DESCRIBE (3)SETUP (4)PLAY (5)PAUSE (6)TEARDOWN ...

  7. 一个基于JRTPLIB的轻量级RTSP客户端(myRTSPClient)——实现篇:(八)RTP音视频传输解析层之MPA传输格式

    一.MPEG RTP音频传输 相较H264的RTP传输格式,MPEGE音频传输格式则简单许多. 每一包MPEG音频RTP包都前缀一个4字节的Header,如下图(RFC2550) “MBZ”必须为0( ...

  8. 一个基于JRTPLIB的轻量级RTSP客户端(myRTSPClient)——实现篇:(七)RTP音视频传输解析层之H264传输格式

    一.H264传输封包格式的2个概念 (1)组包模式(Packetization Modes) RFC3984中定义了3种组包模式:单NALU模式(Single Nal Unit Mode).非交错模式 ...

  9. 一个基于JRTPLIB的轻量级RTSP客户端(myRTSPClient)——实现篇:(六)RTP音视频传输解析层之音视频数据传输格式

    一.差异 本地音视频数据格式和用来传输的音视频数据格式存在些许差异,由于音视频数据流到达客户端时,需要考虑数据流的数据边界.分包.组包顺序等问题,所以传输中的音视频数据往往会多一些字节. 举个例子,有 ...

  10. 一个基于JRTPLIB的轻量级RTSP客户端(myRTSPClient)——实现篇:(九)以g711-mulaw为例添加新的编码格式解析支持

    一.myRtspClient音频解析架构 AudioTypeBase是处理解析各种编码的音频数据的接口类.处理MPA数据的MPEG_Audio类和处理g711-mulaw的PCMU_Audio类均从A ...

随机推荐

  1. 是否使用安全模式启动word

          打开word,出现了一个提示,显示着“word遇到问题需要关闭.我们对此引起的不便表示抱歉.”下面有选项“恢复我的工作并重启word”,选中它.点下面的“不发送”.      在出现的提示 ...

  2. 面向对象15.3String类-常见功能-获取-1

    API使用: 查API文档的时候,有很多方法,首先先看返回的类型 下面的方法函数有的是有覆写Object类的如1.1图,如果没有复写的话是写在1.2图片那里的,如果找到了相对于的方法,可以点击进去可以 ...

  3. MySql单表最大8000W+ 之数据库遇瓶颈记

    前言 昨晚救火到两三点,早上七点多醒来,朦胧中醒来发现电脑还开着,赶紧爬起来看昨晚执行的SQL命令结果.由于昨晚升级了阿里云的RDS,等了将近两个小时 还在 升降级中,早上阿里云那边回复升级过程中出现 ...

  4. shell脚本中字符串的常见操作及"command not found"报错处理(附源码)

    简介 昨天在通过shell脚本实现一个功能的时候,由于对shell处理字符串的方法有些不熟悉导致花了不少时间也犯了很多错误,因此将昨日的一些错误记录下来,避免以后再犯. 字符串的定义与赋值 # 定义S ...

  5. 【.net 深呼吸】自己动手来写应用程序设置类

    在开始装逼之前,老周先说明一件事.有人说老周写的东西太简单了,能不能写点复杂点.这问题就来了,要写什么东西才叫“复杂”?最重要的是,写得太复杂了,一方面很多朋友看不懂,另一方面,连老周自己也不知道怎么 ...

  6. EL函数和自定义EL函数

    简介 EL原本是JSTL1.0中的技术(所以EL和JSTL感情如此好就是自然的了),但是从JSP2.0开始,EL就分离出来纳入了JSP的标准了.但是EL函数还是和JSTL技术绑定在一起.下面将介绍如何 ...

  7. 处理SFTP服务器上已离职用户,设置为登录禁用状态

    测试用户禁用SQL select Enabled,LoginID from suusers where LoginID = 'yangwl' update suusers set Enabled=1 ...

  8. ARM开发(1) 基于STM32的LED跑马灯

    一 跑马灯原理:  1.1 本实验实现2个led的跑马灯效果,即2个led交替闪烁.  1.2 实验思路:根据电路图原理,给led相关引脚赋予高低电平,实现电路的导通,使led灯发光.  1.3 开发 ...

  9. 【Log4j】分包,分等级记录日志信息

    在开发中我们经常会将不同包下的日志信息在不同的地方输出,以便于以后出问题能够直接在对应的文件中找到对应的信息! 例如:在spring+SpringMVC+mybatis的框架中,我们经常会将sprin ...

  10. Linux文件系统,ntfs分区显示只读文件系统,提示超级快损坏

    背景:某天当我打开自己的设备,突然发现ntfs分区无法写入任何文件,提示为只读文件系统,具体现象如下: 修复过程:排除权限问题,使用fsck进行修复无果后,使用e2fsck进行修复 显示超级快损坏,这 ...