請注意以下命令/事例均基于Mac環(huán)境
FFmpeg采集音頻
-
通過命令方式
//采集
ffmpeg -f avfoundation -i :0 out.wav
//播放
ffplay out.wav
-
通過API方式



重要api講解
av_read_frame //可以讀取音頻/視頻數(shù)據(jù)
av_init_packet
av_packet_unref
av_packet_alloc //此方法先分配空間再調(diào)用av_init_packet
av_packet_free //此方法先調(diào)用av_packet_unref解引用再釋放空間
事例
.h文件
#include <stdio.h>
#include "libavutil/avutil.h"
#include "libavdevice/avdevice.h"
#include "libavformat/avformat.h"
#include "libavcodec/avcodec.h"
void rec_audio(void);
.m文件
#include "testc.h"
void rec_audio() {
int ret = 0;
char errors[1024] = {0, };
AVFormatContext *fmt_ctx = NULL;
AVDictionary *options = NULL;
int count = 0;
AVPacket pkt;
//[[video device]:[audio device]]
char *devicename = ":0";
av_log_set_level(AV_LOG_DEBUG);
//注冊設(shè)備
avdevice_register_all();
//設(shè)置采集方式
AVInputFormat *iformat = av_find_input_format("avfoundation");
//打開音頻設(shè)備
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;
}
//寫入文件 w:寫入 b:二進制 +:文件不存在就自動創(chuàng)建
char *out = "/Users/mac/Downloads/my_av_base.pcm";
FILE *outfile = fopen(out, "wb+");
av_init_packet(&pkt);
//讀取音頻數(shù)據(jù)
while ((ret = av_read_frame(fmt_ctx, &pkt)) == 0 && count++ < 500) {
//寫入文件
fwrite(pkt.data, pkt.size, 1, outfile);
fflush(outfile);
av_log(NULL, AV_LOG_INFO, "pkt size is %d(%p), count=%d \n",pkt.size, pkt.data, count);
//釋放資源
av_packet_unref(&pkt);
}
//關(guān)閉文件
fclose(outfile);
//關(guān)閉設(shè)備
avformat_close_input(&fmt_ctx);
av_log(NULL, AV_LOG_DEBUG, "finish!\n");
}
ViewController.swift
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.setFrameSize(NSSize(width: 700, height: 300))
let btn = NSButton.init(title: "button", target: self, action: #selector(myfunc))
btn.frame = NSRect(x: 50, y: 60, width: 90, height: 30);
self.view.addSubview(btn)
}
@objc func myfunc() {
rec_audio()
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
播放
ffplay -ar 44100 -ac 2 -f f32le my_av_base.pcm