arecord -l
**** List of CAPTURE Hardware Devices ****
card 0: PCH [HDA Intel PCH], device 0: ALC662 rev3 Analog [ALC662 rev3 Analog]
Subdevices: 1/1
Subdevice #0: subdevice #0
card 0: PCH [HDA Intel PCH], device 2: ALC662 rev3 Alt Analog [ALC662 rev3 Alt Analog]
Subdevices: 1/1
Subdevice #0: subdevice #0
card 2: U0x46d0x825 [USB Device 0x46d:0x825], device 0: USB Audio [USB Audio]
Subdevices: 1/1
Subdevice #0: subdevice #0
表示设备可以用hw后面加参数表示,其含义如下:
hw:<X>,<Y>, where <X>=card, <Y>=device
#define __STDC_CONSTANT_MACROS
#include <string.h>
extern "C"
{
#include "libavutil/avutil.h"
#include "libavdevice/avdevice.h"
#include "libavformat/avformat.h"
#include "libavcodec/avcodec.h"
#include "libswresample/swresample.h"
#include "libavdevice/avdevice.h"
}
/**
* @brief open audio device
* @return succ: AVFormatContext*, fail: NULL
*/
static
AVFormatContext* open_dev(){
int ret = 0;
char errors[1024] = { 0, };
//ctx
AVFormatContext *fmt_ctx = NULL;
AVDictionary *options = NULL;
av_dict_set(&options, "sample_size", "16", 0);
av_dict_set(&options, "channels", "1", 0);
av_dict_set(&options, "sample_rate", "44100", 0);
//[[video device]:[audio device]]
char *device_name = "hw:2,0";
//get format
AVInputFormat *iformat = av_find_input_format("alsa");
//open device
if ((ret = avformat_open_input(&fmt_ctx, device_name, iformat, &options)) < 0){
av_strerror(ret, errors, 1024);
fprintf(stderr, "Failed to open audio device, [%d]%s\n", ret, errors);
return NULL;
}
return fmt_ctx;
}
void rec_audio() {
//context
AVFormatContext *fmt_ctx = NULL;
//set log level
av_log_set_level(AV_LOG_DEBUG);
//register audio device
avdevice_register_all();
//create file
char *out = "/home/lili/Videos/16k_mono_s16le.pcm";
FILE *outfile = fopen(out, "wb+");
if (!outfile){
printf("Error, Failed to open file!\n");
return;
}
//打开设备
fmt_ctx = open_dev();
if (!fmt_ctx){
printf("Error, Failed to open device!\n");
return;
}
AVPacket pkt;
int ret = -1, count = 1;
while((ret = av_read_frame(fmt_ctx, &pkt)) == 0 && count++ < 1024)
{
av_log(NULL, AV_LOG_INFO, "packet size is %d\n", pkt.size);
fwrite(pkt.data, pkt.size, 1, outfile);
fflush(outfile);
av_packet_unref(&pkt);//release pkt
}
fclose(outfile);
av_log(NULL, AV_LOG_DEBUG, "finish!\n");
return;
}
int main(int argc, char *argv[])
{
rec_audio();
return 0;
}
本机默认采集的是16000采样率&单通道&16位采样大小
ffplay -ar 16000 -channels 1 -f s16le /home/lili/Videos/16k_mono_s16le.pcm