Qt+FFMPEG学习(三)音频录制(dshow)

#include <QCoreApplication>

extern "C"{
    #include "libavcodec/avcodec.h"
    #include "libavformat/avformat.h"
    #include "libswscale/swscale.h"
    #include "libavdevice/avdevice.h"
    #include "libavformat/avio.h"
    #include "libavutil/imgutils.h"
}
#include <QDebug>
#include <QFile>

int main(int argc, char *argv[])
{
    avdevice_register_all();
    AVFormatContext *formatContext = avformat_alloc_context();
    AVInputFormat *inputFormat = av_find_input_format("dshow");
    QString url="audio=立体声混音 (Realtek High Definition Audio)";
    if(avformat_open_input(&formatContext,url.toUtf8().data(),inputFormat,nullptr)!=0){
        qDebug()<<"can`t open input device";
        return -1;
    }
    int audioIndex=-1;
    for(uint i=0;i<formatContext->nb_streams;i++){
        if(formatContext->streams[i]->codecpar->codec_type==AVMEDIA_TYPE_AUDIO){
            audioIndex=i;
            break;
        }
    }
    
    AVCodecParameters *codecParamter=formatContext->streams[audioIndex]->codecpar;
    AVCodec* codec=avcodec_find_decoder(codecParamter->codec_id);
    AVCodecContext* codecContext=avcodec_alloc_context3(codec);
    avcodec_parameters_to_context(codecContext,codecParamter);
    avcodec_open2(codecContext,codec,nullptr);
    
    AVFrame *frame = av_frame_alloc();
    AVPacket *packet= av_packet_alloc();
    QFile file("output2.pcm");
    if(!file.open(QFile::WriteOnly)){
        qDebug()<<"can`t open file";
        return -1;
    }
    
    qDebug()<<"audio info:"<<endl
           <<codecParamter->format<<codecParamter->bit_rate<<codecParamter->sample_rate<<codecParamter->channels;
    
    float time = 0;
    while (time<=10.0) {
        if(av_read_frame(formatContext,packet)!=0){
            qDebug()<<"can`t read frame";
            return -1;
        }
        if(packet->stream_index==audioIndex){
            if(avcodec_send_packet(codecContext,packet)!=0){
                continue;
            }
            if(avcodec_receive_frame(codecContext,frame)!=0){
                continue;
            }

            int pcmSize=av_samples_get_buffer_size(nullptr,codecParamter->channels,frame->nb_samples,codecContext->sample_fmt,1);
            float usedTime = frame->nb_samples*1.0/codecParamter->sample_rate;
            time+=usedTime;
            qDebug()<<pcmSize<<usedTime<<time;
            file.write((char*)frame->data[0],pcmSize);
            av_packet_unref(packet);
        }
    }
    av_frame_free(&frame);
    av_packet_free(&packet);
    avformat_close_input(&formatContext);
    avcodec_free_context(&codecContext);
    avformat_free_context(formatContext);
    file.close();
    return 0;
}

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值