Audio Recorder C++ FFmpeg 4.2 on Windows
using Visual Studio 2019
1.Install VBCable
Set up
reference: https://mediarealm.com.au/articles/stereo-mix-setup-windows-10/
2.Set up C++ property & Linker property in project property
(Linker : add Winmm.lib; in somewhere)
3.-----------------------------Souce.cpp---------------------------
#define _CRT_SECURE_NO_WARNINGS
//#include <QDebug>
//#include <QByteArray>
#include <stdio.h>
#include <iostream>
#define __STDC_CONSTANT_MACROS
extern "C" {
#include <libavutil/avassert.h>
#include <libavutil/channel_layout.h>
#include <libavutil/opt.h>
#include <libavutil/mathematics.h>
#include <libavutil/timestamp.h>
#include <libavformat/avformat.h>
//#include "libavutil/imgutils.h"
#include <libswscale/swscale.h>
#include <libswresample/swresample.h>
}
#include <windows.h>
using namespace std;
const int NUMPTS = 44100 * 5;
int sampleRate = 44100;
int channels = 2;
int bitPerSample = 16;
int bytePerSample = 4;
/* Following field are set by program */
int nb_samples;
//short int* waveIn; // BlockAlign * 441
BYTE* waveIn; // BlockAlign * 441
HWAVEIN hWaveIn;
WAVEHDR WaveInHdr;
MMRESULT result;
HWAVEOUT hWaveOut;
WAVEFORMATEX pFormat;
FILE* fp;
AVFormatContext* oc;
/****************************/
typedef struct OutputStream {
AVStream* st;
AVCodecContext* enc;
/* pts of the next frame that will be generated */
int64_t next_pts;
int samples_count;
AVFrame* frame;
AVFrame* tmp_frame;
float t, tincr, tincr2;
struct SwsContext* sws_ctx;
struct SwrContext* swr_ctx;
} OutputStream;
OutputStream audio_st = { 0 };
static int write_frame(AVFormatContext* fmt_ctx, const AVRational* time_base, AVStream* st, AVPacket* pkt)
{
/* rescale output packet timestamp values from codec to stream timebase */
av_packet_rescale_ts(pkt, *time_base, st->time_base);
pkt->stream_index = st->index;
/* Write the compressed frame to the media file. */
//log_packet(fmt_ctx, pkt);
return av_interleaved_write_frame(fmt_ctx, pkt);
}
static void add_stream(OutputStream* ost, AVFormatContext* oc, AVCodec** codec, enum AVCodecID codec_id)
{
AVCodecContext* c;
int i;
/* find the encoder */
*codec = avcodec_find_encoder(codec_id);
if (!(*codec)) {
fprintf(stderr, "Could not find encoder for '%s'\n",
avcodec_get_name(codec_id));
exit(1);
}
ost->st = avformat_new_stream(oc, NULL);
if (!ost->st) {
fprintf(stderr, "Could not allocate stream\n");
exit(1);
}
ost->st->id = oc->nb_streams - 1;
c = avcodec_alloc_context3(*codec);
if (!c) {
fprintf(stderr, "Could not alloc an encoding context\n");
exit(1);
}
ost->enc = c;
switch ((*codec)->type) {
case AVMEDIA_TYPE_AUDIO:
c->sample_fmt = (*codec)->sample_fmts ?
(*codec)->sample_fmts[0] : AV_SAMPLE_FMT_FLTP;
c->bit_rate = 64000;
c->sample_rate = 44100;
if ((*codec)->supported_samplerates) {
c->sample_rate = (*codec)->supported_samplerates[0];
for (i = 0; (*codec)->supported_samplerates[i]; i++) {
if ((*codec)->supported_samplerates[i] == 44100)
c->sample_rate = 44100;
}
}
c->channels = av_get_channel_layout_nb_channels(c->channel_layout);
c->channel_layout = AV_CH_LAYOUT_STEREO;
if ((*codec)->channel_layouts) {
c->channel_layout = (*codec)->channel_layouts[0];
for (i = 0; (*codec)->channel_layouts[i]; i++) {
if ((*codec)->channel_layouts[i] == AV_CH_LAYOUT_STEREO)
c->channel_layout = AV_CH_LAYOUT_STEREO;
}
}
c->channels = av_get_channel_layout_nb_channels(c->channel_layout);
//ost->st->time_base = (AVRational){ 1, c->sample_rate };
ost->st->time_base.num = 1;
ost->st->time_base.den = c->sample_rate;
break;
default:
break;
}
/* Some formats want stream headers to be separate. */
if (oc->oformat->flags & AVFMT_GLOBALHEADER)
c->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
}
static AVFrame* alloc_audio_frame(enum AVSampleFormat sample_fmt,
uint64_t channel_layout,
int sample_rate, int nb_samples)
{
AVFrame* frame = av_frame_alloc();
int ret;
if (!frame) {
fprintf(stderr, "Error allocating an audio frame\n");
exit(1);
}
frame->format = sample_fmt;
frame->channel_layout = channel_layout;
frame->sample_rate = sample_rate;
frame->nb_samples = nb_samples;
if (nb_samples) {
ret = av_frame_get_buffer(frame, 0);
if (ret < 0) {
fprintf(stderr, "Error allocating an audio buffer\n");
exit(1);
}
}
return frame;
}
static void open_audio(AVFormatContext* oc, AVCodec* codec, OutputStream* ost, AVDictionary* opt_arg)
{
AVCodecContext* c;
//int nb_samples;
int ret;
AVDictionary* opt = NULL;
c = ost->enc;
/* open it */
av_dict_copy(&opt, opt_arg, 0);
ret = avcodec_open2(c, codec, &opt);
av_dict_free(&opt);
if (ret < 0) {
//fprintf(stderr, "Could not open audio codec: %s\n", av_err2str(ret));
fprintf(stderr, "Could not open audio codec: \n");
exit(1);
}
if (c->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE)
nb_samples = 4410;
else
nb_samples = c->frame_size;
cout << "nb_samples : " << nb_samples << endl;
ost->frame = alloc_audio_frame(c->sample_fmt, c->channel_layout,
c->sample_rate, nb_samples);
ost->tmp_frame = alloc_audio_frame(AV_SAMPLE_FMT_S16, c->channel_layout,
c->sample_rate, nb_samples);
/* copy the stream parameters to the muxer */
ret = avcodec_parameters_from_context(ost->st->codecpar, c);
if (ret < 0) {
fprintf(stderr, "Could not copy the stream parameters\n");
exit(1);
}
/* create resampler context */
ost->swr_ctx = swr_alloc();
if (!ost->swr_ctx) {
fprintf(stderr, "Could not allocate resampler context\n");
exit(1);
}
/* set options */
av_opt_set_int(ost->swr_ctx, "in_channel_count", c->channels, 0);
av_opt_set_int(ost->swr_ctx, "in_sample_rate", c->sample_rate, 0);
av_opt_set_sample_fmt(ost->swr_ctx, "in_sample_fmt", AV_SAMPLE_FMT_S16, 0);
av_opt_set_int(ost->swr_ctx, "out_channel_count", c->channels, 0);
av_opt_set_int(ost->swr_ctx, "out_sample_rate", c->sample_rate, 0);
av_opt_set_sample_fmt(ost->swr_ctx, "out_sample_fmt", c->sample_fmt, 0);
/* initialize the resampling context */
if ((ret = swr_init(ost->swr_ctx)) < 0) {
fprintf(stderr, "Failed to initialize the resampling context\n");
exit(1);
}
}
/* Prepare a 16 bit dummy audio frame of 'frame_size' samples and
* 'nb_channels' channels. */
static AVFrame* get_audio_frame(OutputStream* ost)
{
AVFrame* frame = ost->tmp_frame;
AVRational temp;
temp.num = 1;
temp.den = 1;
/* check if we want to generate more frames */
/*if (av_compare_ts(ost->next_pts, ost->enc->time_base,
STREAM_DURATION, temp) >= 0)
return NULL;*/
//frame->data[0] = (uint8_t*)waveIn;
for (int i = 0; i < nb_samples * bytePerSample; i++)
frame->data[0][i] = waveIn[i];
frame->pts = ost->next_pts;
ost->next_pts += frame->nb_samples;
return frame;
}
static int write_audio_frame(AVFormatContext* oc, OutputStream* ost)
{
AVCodecContext* c;
AVPacket pkt = { 0 }; // data and size must be 0;
AVFrame* frame;
int ret;
int got_packet;
int dst_nb_samples;
av_init_packet(&pkt);
c = ost->enc;
frame = get_audio_frame(ost);
if (frame) {
/* convert samples from native format to destination codec format, using the resampler */
/* compute destination number of samples */
dst_nb_samples = av_rescale_rnd(swr_get_delay(ost->swr_ctx, c->sample_rate) + frame->nb_samples,
c->sample_rate, c->sample_rate, AV_ROUND_UP);
av_assert0(dst_nb_samples == frame->nb_samples);
/* when we pass a frame to the encoder, it may keep a reference to it
* internally;
* make sure we do not overwrite it here
*/
ret = av_frame_make_writable(ost->frame);
if (ret < 0)
exit(1);
/* convert to destination format */
ret = swr_convert(ost->swr_ctx,
ost->frame->data, dst_nb_samples,
(const uint8_t**)frame->data, frame->nb_samples);
if (ret < 0) {
fprintf(stderr, "Error while converting\n");
exit(1);
}
frame = ost->frame;
AVRational temp;
temp.num = 1;
temp.den = c->sample_rate;
//frame->pts = av_rescale_q(ost->samples_count, (AVRational) { 1, c->sample_rate }, c->time_base);
frame->pts = av_rescale_q(ost->samples_count, temp, c->time_base);
ost->samples_count += dst_nb_samples;
}
//ret = avcodec_encode_audio2(c, &pkt, frame, &got_packet);
ret = avcodec_send_frame(c, frame);
if (ret < 0) {
//fprintf(stderr, "Error encoding audio frame: %s\n", av_err2str(ret));
fprintf(stderr, "Error encoding audio frame: \n");
if (ret == AVERROR_EOF)
return 1;
exit(1);
}
got_packet = 1;
while (ret >= 0) {
ret = avcodec_receive_packet(c, &pkt);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
got_packet = 0;
return 0;
}
if (write_frame(oc, &c->time_base, ost->st, &pkt) < 0) {
fprintf(stderr, "Error while writing audio frame: \n");
exit(1);
}
}
return (frame || got_packet) ? 0 : 1;
}
static void close_stream(AVFormatContext* oc, OutputStream* ost)
{
avcodec_free_context(&ost->enc);
av_frame_free(&ost->frame);
av_frame_free(&ost->tmp_frame);
sws_freeContext(ost->sws_ctx);
swr_free(&ost->swr_ctx);
}
void CALLBACK waveInProc(HWAVEIN hwi, UINT uMsg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2)
{
//printf("(waveInProc) hWaveIn 0x%p, nMessage 0x%04X, nInstance %d, nParameter1 %d, nParameter2 %d\n", hwi, uMsg, dwInstance, dwParam1, dwParam2);
//cout << "waveInProc()..." << endl;
WAVEHDR* pHdr = NULL;
WAVEHDR pHdr2;
switch (uMsg)
{
case WIM_CLOSE:
cout << "waveInProc()... WIM_CLOSE" << endl;
break;
case WIM_DATA:
{
pHdr = (WAVEHDR*)dwParam1;
pHdr2.lpData = (LPSTR)pHdr->lpData;
pHdr2.dwBufferLength = pHdr->dwBufferLength;
pHdr2.dwBytesRecorded = pHdr->dwBytesRecorded;
pHdr2.dwUser = 0;
pHdr2.dwFlags = 0;
pHdr2.dwLoops = 0;
cout << "waveInProc()... WIM_DATA : " << "pHdr->dwBufferLength:" << pHdr->dwBufferLength << " pHdr->dwBytesRecorded:" << pHdr->dwBytesRecorded << endl;//!
//cout << QByteArray(pHdr->lpData, pHdr->dwBytesRecorded).toHex().constData() << " : " << QByteArray(pHdr->lpData, pHdr->dwBytesRecorded).length() << endl;
//waveOutPrepareHeader(hWaveOut, &pHdr2, sizeof(WAVEHDR));//!
//waveOutWrite(hWaveOut, &pHdr2, sizeof(WAVEHDR));//!
//cout << "buffer : " << pHdr->lpData[0] << pHdr->lpData[1] << endl;
write_audio_frame(oc, &audio_st);
fwrite(pHdr->lpData, 1, pHdr->dwBytesRecorded, fp);
waveInPrepareHeader(hwi, pHdr, sizeof(WAVEHDR));
waveInAddBuffer(hwi, pHdr, sizeof(WAVEHDR));
}
break;
case WIM_OPEN:
cout << "waveInProc()... WIM_OPEN" << endl;
break;
default:
break;
}
}
int main(int argv, char** args)
{
const char* filename = "output.mp3";
AVOutputFormat* fmt;
//AVFormatContext* oc;
AVCodec* audio_codec = NULL;
int ret;
int have_audio = 0;
//int encode_video = 0, encode_audio = 0;
AVDictionary* opt = NULL;
fp = fopen("capture.pcm", "ab+");
if (!fp) {
cout << "fail to open file.\n" << endl;
return 1;
}
pFormat.wFormatTag = WAVE_FORMAT_PCM;
pFormat.nChannels = channels;
pFormat.nSamplesPerSec = sampleRate;
pFormat.wBitsPerSample = bitPerSample;
//pFormat.nAvgBytesPerSec = 2 * sampleRate;
pFormat.nAvgBytesPerSec = pFormat.nSamplesPerSec * pFormat.nChannels * pFormat.wBitsPerSample / 8;
//pFormat.nBlockAlign = 2;
pFormat.nBlockAlign = pFormat.nChannels * pFormat.wBitsPerSample / 8;
pFormat.cbSize = 0;
result = waveInOpen(&hWaveIn, WAVE_MAPPER, &pFormat, (DWORD_PTR)waveInProc, NULL, CALLBACK_FUNCTION);
if (result)
{
char fault[256];
waveInGetErrorTextA(result, fault, 256);
MessageBoxA(NULL, fault, "Failed to open waveform input device.", MB_OK | MB_ICONEXCLAMATION);
return 1;
}
//--------------------------------------
avformat_alloc_output_context2(&oc, NULL, NULL, filename);
if (!oc) {
printf("Could not deduce output format from file extension: using MPEG.\n");
avformat_alloc_output_context2(&oc, NULL, "mpeg", filename);
}
if (!oc)
return 1;
fmt = oc->oformat;
/* Add the audio and video streams using the default format codecs
* and initialize the codecs. */
if (fmt->audio_codec != AV_CODEC_ID_NONE) {
add_stream(&audio_st, oc, &audio_codec, fmt->audio_codec);
have_audio = 1;
//encode_audio = 1;
}
/* Now that all the parameters are set, we can open the audio and
* video codecs and allocate the necessary encode buffers. */
if (have_audio)
open_audio(oc, audio_codec, &audio_st, opt);
av_dump_format(oc, 0, filename, 1);
/* open the output file, if needed */
if (!(fmt->flags & AVFMT_NOFILE)) {
ret = avio_open(&oc->pb, filename, AVIO_FLAG_WRITE);
if (ret < 0) {
//fprintf(stderr, "Could not open '%s': %s\n", filename, av_err2str(ret));
fprintf(stderr, "Could not open '%s': \n", filename);
return 1;
}
}
/* Write the stream header, if any. */
ret = avformat_write_header(oc, &opt);
if (ret < 0) {
//fprintf(stderr, "Error occurred when opening output file: %s\n", av_err2str(ret));
fprintf(stderr, "Error occurred when opening output file: \n");
return 1;
}
//--------------------------------------
//waveIn = new short int[nb_samples * bytePerSample];
waveIn = new BYTE[nb_samples * bytePerSample];
WaveInHdr.lpData = (LPSTR)waveIn;
WaveInHdr.dwBufferLength = nb_samples * bytePerSample;
WaveInHdr.dwBytesRecorded = 0;
WaveInHdr.dwUser = 0;
WaveInHdr.dwFlags = 0;
WaveInHdr.dwLoops = 0;
waveInPrepareHeader(hWaveIn, &WaveInHdr, sizeof(WAVEHDR));
cout << "WaveInHdr.dwBufferLength : " << WaveInHdr.dwBufferLength << endl;
result = waveInAddBuffer(hWaveIn, &WaveInHdr, sizeof(WAVEHDR));
if (result)
{
MessageBoxA(NULL, "Failed to read block from device", NULL, MB_OK | MB_ICONEXCLAMATION);
return 1;
}
result = waveInStart(hWaveIn);
if (result)
{
MessageBoxA(NULL, "Failed to start recording", NULL, MB_OK | MB_ICONEXCLAMATION);
return 1;
}
/*if (waveOutOpen(&hWaveOut, WAVE_MAPPER, &pFormat, 0, 0, WAVE_FORMAT_DIRECT))
{
MessageBoxA(NULL, "Failed to replay", NULL, MB_OK | MB_ICONEXCLAMATION);
}*/ //!
Sleep((NUMPTS / sampleRate) * 1000);
//waveOutUnprepareHeader(hWaveOut, &WaveInHdr, sizeof(WAVEHDR));//!
//waveOutClose(hWaveOut);//!
waveInUnprepareHeader(hWaveIn, &WaveInHdr, sizeof(WAVEHDR));
waveInStop(hWaveIn);
waveInClose(hWaveIn);
AVPacket pkt = { 0 }; // data and size must be 0;
av_init_packet(&pkt);
ret = avcodec_send_frame(audio_st.enc, NULL);
/*if (ret < 0) {
//fprintf(stderr, "Error encoding audio frame: %s\n", av_err2str(ret));
fprintf(stderr, "Error encoding audio frame: \n");
if (ret == AVERROR_EOF)
return 1;
exit(1);
}*/
while (ret >= 0) {
ret = avcodec_receive_packet(audio_st.enc, &pkt);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
}
if (write_frame(oc, &audio_st.enc->time_base, audio_st.st, &pkt) < 0) {
fprintf(stderr, "Error while writing audio frame: \n");
exit(1);
}
}
av_write_trailer(oc);
/* Close each codec. */
if (have_audio)
close_stream(oc, &audio_st);
if (!(fmt->flags & AVFMT_NOFILE))
/* Close the output file. */
avio_closep(&oc->pb);
/* free the stream */
avformat_free_context(oc);
fclose(fp);
return 0;
}
---------------------------------------------------------------------------------------------
reference: https://kldp.org/node/135620
4. Usage : play sound and run it, it will record what you're playing and store it to capture.pcm & output.mp3 file
5.enter commend to convert .pcm to .wav
>ffmpeg -f s16le -ar 44.1k -ac 2 -i capture.pcm output.wav
留言
張貼留言