QT开发中文网

写一段代码要求Windows系统 Qt平台下,用FFmpeg打开音频设备

#include #include

AVFormatContext* pFormatCtx = NULL; AVCodecContext* pCodecCtxOrig = NULL; AVCodecContext* pCodecCtx = NULL;

// Find the audio device QAudioDeviceInfo inputDevice(QAudioDeviceInfo::defaultInputDevice()); if (!inputDevice.isFormatSupported(format)) {

qWarning() << "Default format not supported - trying to use nearest";
format = inputDevice.nearestFormat(format);

}

// Open the audio device QAudioInput* audioInput = new QAudioInput(inputDevice, format); audioInput->start();

// Initialize FFmpeg’s AVFormatContext and AVCodecContext for reading from the audio device pFormatCtx = avformat_alloc_context(); pCodecCtxOrig = avcodec_alloc_context3(NULL); pCodecCtx = avcodec_alloc_context3(avcodec_find_decoder(AV_CODEC_ID_PCM_S16LE));

if (avformat_open_input(&pFormatCtx, “”, av_find_input_format(“alsa”), NULL) != 0) {

printf("Couldn't open input stream.\n");
return -1;

}

if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {

printf("Couldn't find stream information.\n");
return -1;

}

int audioStreamIndex = av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_AUDIO, -1, -1, &decoder, 0);

if (audioStreamIndex < 0) {

printf("Could not find any audio stream in the input file\n");
return -1;

}

avcodec_parameters_to_context(pCodecCtxOrig, pFormatCtx->streams[audioStreamIndex]->codecpar); av_codec_set_pkt_timebase(pCodecCtxOrig, pFormatCtx->streams[audioStreamIndex]->time_base);

// Set decoder parameters pCodecCtx->channels = pCodecCtxOrig->channels; pCodecCtx->channel_layout = av_get_default_channel_layout(pCodecCtxOrig->channels); pCodecCtx->sample_rate = pCodecCtxOrig->sample_rate; pCodecCtx->sample_fmt = AV_SAMPLE_FMT_S16; pCodecCtx->bit_rate = pCodecCtxOrig->bit_rate;

if (avcodec_open2(pCodecCtx, decoder, NULL) < 0) {

printf("Could not open codec.\n");
return -1;

}

AVFrame* frame = av_frame_alloc(); AVPacket packet; av_init_packet(&packet);

// Read packets from the audio device and decode them with FFmpeg while (true) {

QByteArray buffer = audioInput->readAll();
if (buffer.size() <= 0)
    break;

packet.data = reinterpret_cast<uint8_t*>(buffer.data());
packet.size = buffer.size();

while (packet.size > 0)
{
    int gotFrame;
    int len = avcodec_decode_audio4(pCodecCtx, frame, &gotFrame, &packet);

    if (len < 0)
    {
        printf("Error decoding audio frame (%d)\n", len);
        break;
    }

    if (gotFrame)
    {
        // Process the decoded audio frame here
        ...
    }

    packet.size -= len;
    packet.data += len;
}

}

// Clean up FFmpeg resources avcodec_free_context(&pCodecCtxOrig); avcodec_free_context(&pCodecCtx); avformat_close_input(&pFormatCtx);

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=3300

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?