#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);