FFMPEG 录制PCM音频数据

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 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值