FFMPEG学习日记–音频采集PCM
本文记录针对FFMPEG音频采集的方法和基本流程并保存为文件供学习
环境:centos8虚拟机+ffmpeg
命令行采集:
ffmpeg -f alsa -ac 2 -i hw:0,0 out.wav
可以看到命令采用alsa进行设备管理随后采集通道为hw:0,0
代码段:
#include <stdio.h>
#include <libavutil/avutil.h>
#include <libavdevice/avdevice.h>
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
void rec_audio()
{
int ret=0;
char error[1024]={0};
int count=0;
AVPacket pkt;
//register device
avdevice_register_all();
av_log_set_level(AV_LOG_DEBUG);
char deviceName[]="hw:0,0";
AVFormatContext *fmt_ctx=NULL;
AVInputFormat* p_InputFormat=av_find_input_format("alsa");
AVDictionary* avDic=NULL;
if(p_InputFormat==NULL)
{
printf("p_InputFormat is null\n");
return;
}
ret= avformat_open_input(&fmt_ctx, deviceName, p_InputFormat, &avDic);
if(ret<0)
{
av_strerror(ret,error,1024);
printf("avformat_open_input err deviceName[%s] ,ret[%d] ,str[%s]",deviceName,ret,error);
return;
}
av_init_packet(&pkt);
char filename[]="rec_audio.pcm";
FILE *fd=fopen(filename,"wb+");
while((0==av_read_frame (fmt_ctx, &pkt))&&count<500)
{
count++;
printf("av_packct size[%d]\n",pkt.size);
//write file data
fwrite(pkt.data,pkt.size,1,fd);
av_packet_unref(&pkt);
}
fflush(fd);
avformat_close_input(&fmt_ctx);
fclose(fd);
av_log(NULL,AV_LOG_DEBUG,"rec_audio success!\n");
return ;
}
int main(int argc,char* argv[])
{
rec_audio();
return 0;
}
编译方法:
gcc testffmpeg.c -o test `pkg-config --libs --cflags libavutil libavdevice libavformat libavcodec`