在linux 使用FFmpeg,简单录音例程

linux下命令

ffmpeg -f alsa -i hw:0 out.wav

对于麦克风这种硬件设备,与其说是格式,我更觉得这是驱动程序。在linux上,通用的音频驱动程序,就是alsa。这里, -f 指定格式(驱动程序)为alsa, -i 指出文件路径,这里是麦克风地址“hw:0”,最后一个是输出文件路径,这里为当前路径下,保存为 out.wav文件。注意:对于mac和window下,麦克风的硬件格式和地址是差异。

C语言实现

以下是C语言调用FFmpeg的库代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>

#include <libavutil/avutil.h>
#include <libavdevice/avdevice.h>
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>

int main(int argc, char** argv)
{
    int ret = 0;
    char errors[1024];
    int count = 0;
    AVPacket pkt;//数据存放
    char *devicename = "hw:0";//mac: :0
    AVFormatContext *fmt_ctx = NULL;  //记得赋值NULL 上下文
    AVDictionary *options = NULL;
    char *out = "./audio.pcm";
    FILE *outfile = NULL;
    char input_command[128];
    int flag=-1;
    av_log_set_level(AV_LOG_DEBUG);

    avdevice_register_all();  //打开所有设备

    AVInputFormat *iformat = av_find_input_format("alsa");//设置平台格式  mac: avfoundation 
     if( (ret = avformat_open_input(&fmt_ctx, devicename,iformat,&options) )< 0)//传入参数 打开设备
     {
        av_strerror(ret,errors,1024);
        av_log(NULL,AV_LOG_DEBUG,"Failed to open audio device,[%d]%s\n",ret,errors);
        return -1;
     }
    
    av_init_packet(&pkt);//数据初始化 干净的空间;
   
   //create file
    outfile = fopen(out,"wb+");

    flag=fcntl(0,F_GETFL); //获取当前flag

    flag |=O_NONBLOCK; //设置新falg

    fcntl(0,F_SETFL,flag); //更新flag

    while((ret = av_read_frame(fmt_ctx,&pkt)) == 0)
    {
        //write FILE
        fwrite(pkt.data,pkt.size,1,outfile);
        fflush(outfile); 
        if((ret=read(0,input_command,sizeof(input_command))) > 0)
        {
            if(strncmp(input_command, "over",4) == 0)
            {
                av_log(NULL,AV_LOG_DEBUG,"over\n");
                break;
            }
            else
            {
                av_log(NULL,AV_LOG_DEBUG,"请重新输入\n");
            }
            memset(input_command, 0, sizeof(input_command));
        }
       av_log(NULL,AV_LOG_DEBUG,"pkt_size:%d(%p)\n",pkt.size,pkt.data);
       av_packet_unref(&pkt);//缓冲区  内存释放
    }

    fclose(outfile);
    avformat_close_input(&fmt_ctx);
    
    av_log(NULL,AV_LOG_DEBUG,"Finish\n");
    return 0;
}

编译:

  gcc av_log_optimi.c -I/usr/ffmpeg4.1/include -L/usr/ffmpeg4.1/lib -o av_log_optimi -lavutil -lavdevice -lavformat -lavcodec

运行:

./av_log_optimi

输入 over 结束录音。

录音文件播放,使用ffpaly播放


ffplay -ar 44100 -ac 2 -f s16le audio.pcm

ar表示 采样率

ac 表示通道数

f 表示采样大小格式

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小昭dedug

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值