代码如下:
#include "testc.h"
void rec_audio(){
int ret = 0;
char errors[1024] = {0, };
// ctx
AVFormatContext *fmt_ctx = NULL; // init NULL
AVDictionary *options = NULL;
// packet
int count = 0;
AVPacket pkt;
av_init_packet(&pkt);
// [[video device]:[audio device]]
char *devicename = ":0";
// set log level
av_log_set_level(AV_LOG_DEBUG);
// register audio device
avdevice_register_all();
// get format
AVInputFormat *iformat = av_find_input_format("avfoundation");
// open device
if ((ret = avformat_open_input(&fmt_ctx, devicename, iformat, &options)) < 0) {
av_strerror(ret, errors, 1024);
fprintf(stderr, "Failed to open audio device, [%d]%s\n", ret, errors);
return;
}
// create file
char *out = "/Users/wanghe/project/audio.pcm";
FILE *outfile = fopen(out, "wb+");
// read data from device
while (count++ < 20) {
ret = av_read_frame(fmt_ctx, &pkt);
// device not ready, sleep 1s
if (ret == -35) {
av_log(NULL, AV_LOG_WARNING, "device not ready, wait 1s\n");
sleep(1);
continue;
}
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "read data error from device\n");
break;
}
av_log(NULL, AV_LOG_INFO,
"pkt size is %d(%p),count=%d \n",
pkt.size, pkt.data, count);
// write file
fwrite(pkt.data, pkt.size, 1, outfile);
fflush(outfile);
av_packet_unref(&pkt);
}
// close file
fclose(outfile);
// close device and release ctx
avformat_close_input(&fmt_ctx);
av_log(NULL, AV_LOG_DEBUG, "finish!\n");
return;
}
以下是点击button输出的日志
[avfoundation @ 0x7fdf2b90e140] audio device '内建麦克风' opened
device not ready, wait 1s
pkt size is 4096(0x7fdf2b102800),count=2
device not ready, wait 1s
pkt size is 4096(0x7fdf2b102000),count=4
device not ready, wait 1s
pkt size is 4096(0x7fdf2c09ae00),count=6
device not ready, wait 1s
pkt size is 4096(0x7fdf2b102000),count=8
device not ready, wait 1s
pkt size is 4096(0x7fdf2c09ae00),count=10
device not ready, wait 1s
pkt size is 4096(0x7fdf2b102000),count=12
device not ready, wait 1s
pkt size is 4096(0x7fdf2c8b3c00),count=14
device not ready, wait 1s
pkt size is 4096(0x7fdf2c8b3c00),count=16
device not ready, wait 1s
pkt size is 4096(0x7fdf2a85f800),count=18
device not ready, wait 1s
pkt size is 4096(0x7fdf2c813a00),count=20
finish!
麻烦老师帮忙分析下可能的原因,难道是麦克风被其它应用占用了。