FFmpeg库的使用与深度解析:解码音频流流程

本文涉及的产品
云解析 DNS,旗舰版 1个月
全局流量管理 GTM,标准版 1个月
公共DNS(含HTTPDNS解析),每月1000万次HTTP解析
简介: FFmpeg库的使用与深度解析:解码音频流流程

解码音频流:FFmpeg库的使用与深度解析

1. 引言

多媒体处理领域,FFmpeg是一个非常强大的库,它提供了多种工具和接口用于处理音频和视频数据。本文将深入探讨如何使用FFmpeg库进行音频流的解码和重采样。

“Simplicity is the ultimate sophistication.” — Leonardo da Vinci

这句话也适用于编程和数据处理。简单的代码和算法往往更容易维护和扩展。

2. 解封装流程

2.1 注册所有封装器和解封装器

使用av_register_all()函数进行注册。

av_register_all();

2.2 打开文件

使用avformat_open_input()函数打开一个文件或URL。

AVFormatContext* pFormatCtx = nullptr;
avformat_open_input(&pFormatCtx, "input.mp3", nullptr, nullptr);

2.3 查找流信息

使用avformat_find_stream_info()函数查找流信息。

avformat_find_stream_info(pFormatCtx, nullptr);

2.4 获取音频流索引和解码器ID

int audioStream = -1;
for (int i = 0; i < pFormatCtx->nb_streams; i++) {
    if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
        audioStream = i;
        break;
    }
}
AVCodecID codecID = pFormatCtx->streams[audioStream]->codec->codec_id;

3. 解码流程

3.1 获取解码器

使用avcodec_find_decoder()函数获取解码器。

AVCodec* pCodec = avcodec_find_decoder(codecID);

3.2 打开解码器

使用avcodec_open2()函数打开解码器。

AVCodecContext* pCodecCtx = pFormatCtx->streams[audioStream]->codec;
avcodec_open2(pCodecCtx, pCodec, nullptr);

3.3 解码数据

AVPacket packet;
AVFrame* pFrame = av_frame_alloc();
while (av_read_frame(pFormatCtx, &packet) >= 0) {
    if (packet.stream_index == audioStream) {
        avcodec_send_packet(pCodecCtx, &packet);
        avcodec_receive_frame(pCodecCtx, pFrame);
    }
    av_packet_unref(&packet);
}

4. 重采样

4.1 创建SwrContext

SwrContext* swrCtx = swr_alloc();

4.2 设置参数并初始化

swr_alloc_set_opts(swrCtx, ...);
swr_init(swrCtx);

4.3 数据转换和内存释放

swr_convert(swrCtx, ...);
swr_free(&swrCtx);

5. 代码示例

#include <iostream>
#include <cstdio>
#include <vdef.h>
using namespace std;
#define MAX_AUDIO_FRAME_SIZE 192000
//Buffer:存储格式
//|-----------|-------------|
//chunk-------pos---len-----|
static Uint8* audio_chunk;
static int audio_len;  //音频剩余长度
static Uint8* audio_pos;  //静态控制音频播放位置
//注册回调函数  SDL2.0
// udata就是我们给到SDL的指针,stream是我们要把声音数据写入的缓冲区指针,len是缓冲区的大小。
void Fill_audio(void* udata,Uint8* stream,int len)
{
    cout << "Fill_audio len:"<<len<<endl;
    SDL_memset(stream,0,len);
    if(audio_len == 0)
    return ;
    len = (len>audio_len?len:audio_len);   //尽可能为最大音频量
    SDL_MixAudio(stream,audio_pos,len,SDL_MIX_MAXVOLUME); //这里的音量设置为函数要求,不影响硬件音量
    audio_pos +=len;//音频播放位置
    audio_len -=len;//剩余音频长度
}
int main()    //这里main 在SDL_main中被宏定义了用的时候不可以使用int main(省参)
{
 int  l_s32AStreamSubscript = -1;//音频流标志
  avformat_network_init();
  char fillename[] = "E:\\tt.mp3";//播放文件
// 1.Open the input file in the unpacked format
  l_pstFormatCtx = avformat_alloc_context();
  if(avformat_open_input(&l_pstFormatCtx,fillename,NULL,NULL)!=0)
  {
    cout << "[music_error]Could not open source file,exit work_" << fillename <<endl;
    return -1;
  }
  if(avformat_find_stream_info(l_pstFormatCtx,NULL)<0)
  {
    cout << "[music_error]couldn't find stream information" <<endl;
    return -1;
  }
//2. get the index position of the audio stream,
  if(l_pstFormatCtx!=nullptr)
  {
    for (unsigned int i = 0; i < l_pstFormatCtx->nb_streams; ++i)
    {
      if (l_pstFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
        l_s32AStreamSubscript = i;//Audio stream sequence number
    }
  }
  if(l_s32AStreamSubscript == -1)
  {
    cout << "[music_error]Can't find audiostream" <<endl;
    return -1;
  }
//3.Find and open the audio decoder  Codec type or id mismatches
  l_pstAStream= l_pstFormatCtx->streams[l_s32AStreamSubscript];
  l_pstACodec =  avcodec_find_decoder(l_pstAStream->codecpar->codec_id);
  l_pstACodecCtx = avcodec_alloc_context3(l_pstACodec); //Allocation of AVCodecContext memory
  if(l_pstACodecCtx == nullptr || avcodec_parameters_to_context(l_pstACodecCtx, (const AVCodecParameters *)l_pstAStream->codecpar)<0)
  {
      cout << "[music_error]Codec ont find" <<endl;
      return -1;
  }
  if (avcodec_open2(l_pstACodecCtx, l_pstACodec, nullptr) < 0 || l_pstACodec == nullptr)
  {
      cout << "[music_error]Cannot find the corresponding decoder or the file is encrypted" <<SDL_GetError()<<endl;
      return -1;
  }
  if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO|SDL_INIT_TIMER))
  {
    cout << "[music_error]Could not initialize SDL" <<SDL_GetError()<<endl;
    return -1;
  }
  uint64_t out_channel_layout  = AV_CH_LAYOUT_STEREO;  //声道格式
  AVSampleFormat out_sample_fmt = AV_SAMPLE_FMT_S16;   //采样格式
  int out_nb_samples=l_pstACodecCtx->frame_size;   //nb_samples: AAC-1024 MP3-1152  格式大小 /*有的是视频格式数据头为非标准格式,从frame_size中得不到正确的数据大小,只能解码一帧数据后才可以获得*/
  int out_sample_rate = 44100;//采样率 pCodecCtx->sample_rate
  int out_channels = av_get_channel_layout_nb_channels(out_channel_layout);  //根据声道格式返回声道个数
  int out_buffer_size = av_samples_get_buffer_size(NULL,out_channels,out_nb_samples,out_sample_fmt,1);//获取输出缓冲大小
  out_buffer = (uint8_t*)av_malloc(MAX_AUDIO_FRAME_SIZE);
  memset(out_buffer,0,MAX_AUDIO_FRAME_SIZE);
  wanted_spec.freq = out_sample_rate; //采样率
  wanted_spec.format = AUDIO_S16SYS;  //告诉SDL我们将要给的格式
  wanted_spec.channels = out_channels;   //声音的通道数
  wanted_spec.silence = 0;         //用来表示静音的值
  wanted_spec.samples = out_nb_samples;   //格式大小
  wanted_spec.callback = Fill_audio;    //回调函数
  //打开音频设备
  wanted_spec.userdata = l_pstACodecCtx;    //SDL供给回调函数运行的参数
  if (SDL_OpenAudio(&wanted_spec, NULL)<0)
  {
        printf("can't open audio.\n");
        return -1;
  }
   //根据声道数返回默认输入声道格式
  int64_t in_channel_layout = av_get_default_channel_layout(l_pstACodecCtx->channels);
   //音频格式转换准备
  au_convert_ctx = swr_alloc();//等同于au_convert_ctx  = NULL;
  //参数设置:输出格式PCM -- 输入格式  MP3
  au_convert_ctx = swr_alloc_set_opts(au_convert_ctx,out_channel_layout, out_sample_fmt, out_sample_rate,
        in_channel_layout,l_pstACodecCtx->sample_fmt , l_pstACodecCtx->sample_rate,0, NULL);
  swr_init(au_convert_ctx);//初始化
  int index =  0;
  packet = (AVPacket*)av_malloc(sizeof(AVPacket));
  av_init_packet(packet);
  pFrame = av_frame_alloc();
  //解析数据包
  while(av_read_frame(l_pstFormatCtx, packet)>=0)
  {
      if(packet->stream_index == l_s32AStreamSubscript)  //如果为音频标志
      {                 
          //解码一帧音频压缩数据,得到音频像素数据
          if ( avcodec_send_packet(l_pstACodecCtx, packet) != 0)
          {
             cout<<"[audio_decode_frame] avcodec_send_packet failed"<<endl;
          }
          else
          {
      //       cout<<"[audio_decode_frame] avcodec_send_packet successfully"<<endl;
          }
           一个avPacket可能包含多帧数据,所以需要使用while循环一直读取
          while( (avcodec_receive_frame(l_pstACodecCtx, pFrame) )>= 0)
          {
              //数据格式转换
              swr_convert(au_convert_ctx,&out_buffer,MAX_AUDIO_FRAME_SIZE,(const uint8_t**)pFrame->data,pFrame->nb_samples);
              //输出一帧包大小
              printf("index:%5d\t pts:%lld\t packet size:%d\n",index,packet->pts,packet->size);
              index++;
           }
          while(audio_len>0)
            SDL_Delay(1);//延时1ms
         //指向音频数据 (PCM data)
         audio_chunk = (Uint8 *) out_buffer;
         //音频长度
         audio_len =out_buffer_size;
         //当前播放位置
         audio_pos = audio_chunk;
         //开始播放
         SDL_PauseAudio(0);
      }
//      cout<<"[audio_decode_frame]Remove the reference to the previous frame"<<endl;
      av_packet_unref(packet);
      av_frame_unref(pFrame);
  }
     av_packet_free(&packet);
     //释放转换结构体
         swr_free(&au_convert_ctx);
#if USE_SDL
    SDL_CloseAudio();//Close SDL
    SDL_Quit();
#endif
#if WRITEPCM
    fclose(file);
#endif
    av_free(out_buffer);
//free_AVCodecCtx:
    avcodec_close(l_pstACodecCtx);
    // 关闭打开音频文件
    avformat_close_input(&l_pstFormatCtx);
    system("pause");
    return 0;
}

6. 总结

本文详细介绍了如何使用FFmpeg库进行音频流的解封装、解码和重采样。这些步骤虽然看似简单,但每一个函数和接口背后都有深刻的设计哲学。

“The most important property of a program is whether it accomplishes the intention of its user.” — C.A.R. Hoare

在我们的编程学习之旅中,理解是我们迈向更高层次的重要一步。然而,掌握新技能、新理念,始终需要时间和坚持。从心理学的角度看,学习往往伴随着不断的试错和调整,这就像是我们的大脑在逐渐优化其解决问题的“算法”。

这就是为什么当我们遇到错误,我们应该将其视为学习和进步的机会,而不仅仅是困扰。通过理解和解决这些问题,我们不仅可以修复当前的代码,更可以提升我们的编程能力,防止在未来的项目中犯相同的错误。

我鼓励大家积极参与进来,不断提升自己的编程技术。无论你是初学者还是有经验的开发者,我希望我的博客能对你的学习之路有所帮助。如果你觉得这篇文章有用,不妨点击收藏,或者留下你的评论分享你的见解和经验,也欢迎你对我博客的内容提出建议和问题。每一次的点赞、评论、分享和关注都是对我的最大支持,也是对我持续分享和创作的动力。

目录
相关文章
|
1月前
|
数据可视化 算法 数据挖掘
用傅里叶变换解码时间序列:从频域视角解析季节性模式
本文介绍了如何使用傅里叶变换和周期图分析来识别时间序列中的季节性模式,特别是在能源消耗数据中。通过Python实现傅里叶变换和周期图,可以有效提取并量化时间序列中的主要和次要频率成分,克服传统可视化分析的局限性。这对于准确捕捉时间序列中的季节性变化具有重要意义。文章以AEP能源消耗数据为例,展示了如何应用这些方法识别日、周、半年等周期模式。
74 3
用傅里叶变换解码时间序列:从频域视角解析季节性模式
|
4月前
|
数据采集 JavaScript API
网页解析库:BeautifulSoup与Cheerio的选择
网页解析库:BeautifulSoup与Cheerio的选择
|
4月前
|
存储 Go PHP
Go语言中的加解密利器:go-crypto库全解析
在软件开发中,数据安全和隐私保护至关重要。`go-crypto` 是一个专为 Golang 设计的加密解密工具库,支持 AES 和 RSA 等加密算法,帮助开发者轻松实现数据的加密和解密,保障数据传输和存储的安全性。本文将详细介绍 `go-crypto` 的安装、特性及应用实例。
225 0
|
5月前
|
Linux API 开发工具
FFmpeg开发笔记(五十九)Linux编译ijkplayer的Android平台so库
ijkplayer是由B站研发的移动端播放器,基于FFmpeg 3.4,支持Android和iOS。其源码托管于GitHub,截至2024年9月15日,获得了3.24万星标和0.81万分支,尽管已停止更新6年。本文档介绍了如何在Linux环境下编译ijkplayer的so库,以便在较新的开发环境中使用。首先需安装编译工具并调整/tmp分区大小,接着下载并安装Android SDK和NDK,最后下载ijkplayer源码并编译。详细步骤包括环境准备、工具安装及库编译等。更多FFmpeg开发知识可参考相关书籍。
161 0
FFmpeg开发笔记(五十九)Linux编译ijkplayer的Android平台so库
|
5月前
|
SQL Oracle 关系型数据库
SQL整库导出语录:全面解析与高效执行策略
在数据库管理和维护过程中,整库导出是一项常见的需求,无论是为了备份、迁移还是数据分析,掌握如何高效、准确地导出整个数据库至关重要
|
5月前
|
前端开发 JavaScript
pyquery:一个灵活方便的 HTML 解析库
pyquery:一个灵活方便的 HTML 解析库
51 1
|
6月前
|
XML JSON 网络协议
超级好用的C++实用库之字节流解析器
超级好用的C++实用库之字节流解析器
66 3
|
6月前
|
数据采集 存储 JSON
从零到一构建网络爬虫帝国:HTTP协议+Python requests库深度解析
在网络数据的海洋中,网络爬虫遵循HTTP协议,穿梭于互联网各处,收集宝贵信息。本文将从零开始,使用Python的requests库,深入解析HTTP协议,助你构建自己的网络爬虫帝国。首先介绍HTTP协议基础,包括请求与响应结构;然后详细介绍requests库的安装与使用,演示如何发送GET和POST请求并处理响应;最后概述爬虫构建流程及挑战,帮助你逐步掌握核心技术,畅游数据海洋。
112 3
|
6月前
|
缓存 网络协议 分布式数据库
超级好用的C++实用库之DNS解析
超级好用的C++实用库之DNS解析
118 0
|
6月前
|
设计模式 存储 算法
PHP中的设计模式:策略模式的深入解析与应用在软件开发的浩瀚海洋中,PHP以其独特的魅力和强大的功能吸引了无数开发者。作为一门历史悠久且广泛应用的编程语言,PHP不仅拥有丰富的内置函数和扩展库,还支持面向对象编程(OOP),为开发者提供了灵活而强大的工具集。在PHP的众多特性中,设计模式的应用尤为引人注目,它们如同精雕细琢的宝石,镶嵌在代码的肌理之中,让程序更加优雅、高效且易于维护。今天,我们就来深入探讨PHP中使用频率颇高的一种设计模式——策略模式。
本文旨在深入探讨PHP中的策略模式,从定义到实现,再到应用场景,全面剖析其在PHP编程中的应用价值。策略模式作为一种行为型设计模式,允许在运行时根据不同情况选择不同的算法或行为,极大地提高了代码的灵活性和可维护性。通过实例分析,本文将展示如何在PHP项目中有效利用策略模式来解决实际问题,并提升代码质量。

热门文章

最新文章

推荐镜像

更多