"hw0,0"是默认声卡设备
声卡命令规则:
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;
}
运行测试: