FFmpeg實踐記錄六:【實戰(zhàn)】音頻采集

請注意以下命令/事例均基于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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容