ffmpeg 通过libavdevice录音

"hw0,0"是默认声卡设备
image-20210521213127091

声卡命令规则:

card {数字1}: xxxx, device {数字2}: xxxx

我们选择哪个设备,则alsa下对应的声卡名称为:"hw:{数字1},{数字2}


代码:

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavdevice/avdevice.h"

#define RECORD_TIME 10
#define SOUND_CARD "hw:0,0"

int recording = 1;
void alram_handle(int s) {
   recording = 0; 
}

void record_pcm(const char *outfile) {
    signal(SIGALRM, alram_handle);

    // 初始化设备
    avdevice_register_all(); 
    AVInputFormat *in_fmt = av_find_input_format("alsa");
    AVFormatContext *fmt_ctx = avformat_alloc_context();
     
    AVDictionary *option;
    av_dict_set(&option, "sample_rate", "44100", 0);
    av_dict_set(&option, "sample_size", "16", 0);
    av_dict_set(&option, "channels", "2", 0);

    if (avformat_open_input(&fmt_ctx, SOUND_CARD, in_fmt, &option) < 0) {
        printf("failed to open input stream.default.\n");
        goto _Error;
    }
    if (avformat_find_stream_info(fmt_ctx, NULL) < 0) {
        printf("failed to find stream info\n");
        goto _Error;
    }

    // 查找流信息
    int stream_index = -1;
    stream_index = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0);
    if (stream_index < 0) {
        printf("failed to find stream_index\n");
        goto _Error;
    }
    av_dump_format(fmt_ctx, stream_index, SOUND_CARD, 0);

  
    AVPacket *packet = av_packet_alloc();

    FILE *fp = fopen(outfile, "w+");
    alarm(RECORD_TIME);
    while (recording) {
        if (av_read_frame(fmt_ctx, packet) < 0) {
            printf("capture pcm data failed\n");
            break;
        }

        fwrite(packet->data, 1, packet->size, fp);
    }

_Error:
    if (fmt_ctx) {
        avformat_close_input(&fmt_ctx);
        avformat_free_context(fmt_ctx);
    }
    if (fp) fclose(fp);
    if (packet) av_packet_free(&packet);
}

int main(int argc, char const* argv[])
{
    record_pcm("out.pcm");
    return 0;
}

运行测试:

image-20210521221006384
image-20210521224329343

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值