参考文档

COM Coding Practices

Audio File Format Specifications

Core Audio APIs

Loopback Recording

#include <iostream>
#include <fstream>
#include <vector> #include <mmdeviceapi.h>
#include <combaseapi.h>
#include <atlbase.h>
#include <Functiondiscoverykeys_devpkey.h>
#include <Audioclient.h>
#include <Audiopolicy.h> // 利用RAII手法,自动调用 CoUninitialize
class CoInitializeGuard {
public:
CoInitializeGuard()
{
_hr = CoInitializeEx(nullptr, COINIT::COINIT_MULTITHREADED);
} ~CoInitializeGuard()
{
if (_hr == S_OK || _hr == S_FALSE) {
CoUninitialize();
}
} HRESULT result() const { return _hr; } private:
HRESULT _hr;
}; constexpr inline void exit_on_failed(HRESULT hr);
void printEndpoints(CComPtr<IMMDeviceCollection> pColletion);
std::string wchars_to_mbs(const wchar_t* s); int main()
{
HRESULT hr{}; CoInitializeGuard coInitializeGuard;
exit_on_failed(coInitializeGuard.result()); // COM 对象都用 CComPtr 包装,会自动调用 Release
// COM 接口分配的堆变量用 CComHeapPtr 包装,会自动调用 CoTaskMemFree
CComPtr<IMMDeviceEnumerator> pEnumerator;
hr = pEnumerator.CoCreateInstance(__uuidof(MMDeviceEnumerator));
exit_on_failed(hr); // 打印所有可用的音频设备
//CComPtr<IMMDeviceCollection> pColletion;
//hr = pEnumerator->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &pColletion);
//exit_on_failed(hr);
//printEndpoints(pColletion); // 使用默认的 Audio Endpoint,eRender 表示音频播放设备,而不是录音设备
CComPtr<IMMDevice> pEndpoint;
hr = pEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &pEndpoint);
exit_on_failed(hr); // 打印出播放设备的名字,可能包含中文
CComPtr<IPropertyStore> pProps;
hr = pEndpoint->OpenPropertyStore(STGM_READ, &pProps);
exit_on_failed(hr);
PROPVARIANT varName;
PropVariantInit(&varName);
hr = pProps->GetValue(PKEY_Device_FriendlyName, &varName);
exit_on_failed(hr);
std::cout << "select audio endpoint: " << wchars_to_mbs(varName.pwszVal) << std::endl;
PropVariantClear(&varName); // 由 IMMDevice 对象 得到 IAudioClient 对象
CComPtr<IAudioClient> pAudioClient;
hr = pEndpoint->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr, (void**)&pAudioClient);
exit_on_failed(hr); // 获得音频播放设备格式信息
CComHeapPtr<WAVEFORMATEX> pDeviceFormat;
pAudioClient->GetMixFormat(&pDeviceFormat); constexpr int REFTIMES_PER_SEC = 10000000; // 1 reference_time = 100ns
constexpr int REFTIMES_PER_MILLISEC = 10000; // 初始化 IAudioClient 对象
const REFERENCE_TIME hnsRequestedDuration = 2 * REFTIMES_PER_SEC; // 1s
hr = pAudioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_LOOPBACK, hnsRequestedDuration, 0, pDeviceFormat, nullptr);
exit_on_failed(hr); // 获得缓冲区大小
UINT32 bufferFrameCount{};
hr = pAudioClient->GetBufferSize(&bufferFrameCount);
exit_on_failed(hr); // 由 IAudioClient 对象 得到 IAudioCaptureClient 对象,也就是将音频播放设备视为录音设备
CComPtr<IAudioCaptureClient> pCaptureClient;
hr = pAudioClient->GetService(__uuidof(IAudioCaptureClient), (void**)&pCaptureClient);
exit_on_failed(hr); // 开始录音
hr = pAudioClient->Start();
exit_on_failed(hr); const REFERENCE_TIME hnsActualDuration = (long long)REFTIMES_PER_SEC * bufferFrameCount / pDeviceFormat->nSamplesPerSec; std::ofstream ofile("./out.wav", std::ios::binary);
if (!ofile) {
exit(-1);
} // 写入各种 header 信息 constexpr UINT32 sizePlaceholder{};
// master RIFF chunk
ofile.write("RIFF", 4);
ofile.write((const char*)&sizePlaceholder, 4);
ofile.write("WAVE", 4);
// 12 // fmt chunk
ofile.write("fmt ", 4);
UINT32 fmt_ckSize = sizeof(WAVEFORMATEX) + pDeviceFormat->cbSize;
ofile.write((const char*)&fmt_ckSize, 4);
{
auto p = pDeviceFormat.Detach();
ofile.write((const char*)p, fmt_ckSize);
pDeviceFormat.Attach(p);
}
// 8 + fmt_ckSize // fact chunk
bool has_fact_chunt = pDeviceFormat->wFormatTag != WAVE_FORMAT_PCM;
if (has_fact_chunt) {
ofile.write("fact", 4);
UINT32 fact_ckSize = 4;
ofile.write((const char*)&fact_ckSize, 4);
DWORD dwSampleLength{};
ofile.write((const char*)&dwSampleLength, 4);
}
// 12 // data chunk
ofile.write("data", 4);
ofile.write((const char*)&sizePlaceholder, 4); UINT32 data_ckSize = 0; // samples data 的大小
UINT32 frame_count = 0; // 帧数 constexpr int max_duration = 60; // 录制 60s
int seconds{}; // 已经录制的时间 time_t t_begin = time(NULL); //UINT32
do {
// 睡眠一定时间,防止CPU占用率高
Sleep(9); BYTE* pData{}; // samples 数据
UINT32 numFramesAvailable{}; // 缓冲区有多少帧
DWORD dwFlags{}; hr = pCaptureClient->GetBuffer(&pData, &numFramesAvailable, &dwFlags, NULL, NULL);
exit_on_failed(hr); int frame_bytes = pDeviceFormat->nChannels * pDeviceFormat->wBitsPerSample / 8;
int count = numFramesAvailable * frame_bytes;
ofile.write((const char*)pData, count);
data_ckSize += count;
frame_count += numFramesAvailable;
seconds = frame_count / pDeviceFormat->nSamplesPerSec;
std::cout << "numFramesAvailable: " << numFramesAvailable << " seconds: " << seconds << std::endl; hr = pCaptureClient->ReleaseBuffer(numFramesAvailable);
exit_on_failed(hr); } while (seconds < max_duration); // 检测实际花了多久,实际时间 - max_duration = 延迟
time_t t_end = time(NULL);
std::cout << "use wall clock: " << t_end - t_begin << "s" << std::endl; if (data_ckSize % 2) {
ofile.put(0);
++data_ckSize;
} UINT32 wave_ckSize = 4 + (8 + fmt_ckSize) + (8 + data_ckSize);
ofile.seekp(4);
ofile.write((const char*)&wave_ckSize, 4); if (has_fact_chunt) {
ofile.seekp(12 + (8 + fmt_ckSize) + 8);
ofile.write((const char*)&frame_count, 4);
} ofile.seekp(12 + (8 + fmt_ckSize) + 12 + 4);
ofile.write((const char*)&data_ckSize, 4); ofile.close(); //所有 COM 对象和 Heap 都会自动释放
} void printEndpoints(CComPtr<IMMDeviceCollection> pColletion)
{
HRESULT hr{}; UINT count{};
hr = pColletion->GetCount(&count);
exit_on_failed(hr); for (UINT i = 0; i < count; ++i) {
CComPtr<IMMDevice> pEndpoint;
hr = pColletion->Item(i, &pEndpoint);
exit_on_failed(hr); CComHeapPtr<WCHAR> pwszID;
hr = pEndpoint->GetId(&pwszID);
exit_on_failed(hr); CComPtr<IPropertyStore> pProps;
hr = pEndpoint->OpenPropertyStore(STGM_READ, &pProps);
exit_on_failed(hr); PROPVARIANT varName;
PropVariantInit(&varName);
hr = pProps->GetValue(PKEY_Device_FriendlyName, &varName);
exit_on_failed(hr); std::cout << wchars_to_mbs(varName.pwszVal) << std::endl; PropVariantClear(&varName);
}
} constexpr inline void exit_on_failed(HRESULT hr) {
if (FAILED(hr)) {
exit(-1);
}
} // 汉字会有编码问题,全部转成窄字符
std::string wchars_to_mbs(const wchar_t* src)
{
UINT cp = GetACP();
int ccWideChar = (int)wcslen(src);
int n = WideCharToMultiByte(cp, 0, src, ccWideChar, 0, 0, 0, 0); std::vector<char> buf(n);
WideCharToMultiByte(cp, 0, src, ccWideChar, buf.data(), (int)buf.size(), 0, 0);
std::string dst(buf.data(), buf.size());
return dst;
}

使用 Windows Core Audio APs 进行 Loopback Recording 并生成 WAV 文件的更多相关文章

  1. windows core audio apis

    这个播放流程有一次当初不是很理解,做个记录,代码中的中文部分,原文档是有解释的:To move a stream of rendering data through the endpoint buff ...

  2. windows&lunix下node.js实现模板化生成word文件

    最近在做了一个小程序!里面有个功能就是根据用户提交的数据,自动生成一份word文档返回给用户.我也是第一次做这功能,大概思路就是先自己弄一份word模板,后台接受小程序发过来的数据,再根据这些数据将相 ...

  3. Core Audio(一)

    Core Audio APIs core audio apis是vista之后引入的,不使用与之前的windows版本:core audio apis提供访问endpoint devices,比如耳机 ...

  4. Core Audio 在Vista/Win7上实现

    应用范围:Vista / win7, 不支持XP 1. 关于Windows Core Auido APIs 在Windowss Vista及Windows 7操作系统下,微软为应用程序提供了一套新的音 ...

  5. Core Audio(二)

    用户模式音频组件 在windows vista中,core audio apis充当用户模式音频子系统的基础,core audio apis作为用户模式系统组件的一个thin layer,它用来将用户 ...

  6. Windows 7上安装Microsoft Loopback Adapter(微软环回网卡)

    Oracle 安装过程中,先决条件检查遇到如下错误: 正在检查网络配置要求...  检查完成.此次检查的总体结果为: 失败 <<<<  问题: 安装检测到系统的主 IP 地址是 ...

  7. 使用Core Audio实现VoIP通用音频模块

    最近一直在做iOS音频技术相关的项目,由于单项直播SDK,互动直播SDK(iOS/Mac),短视频SDK,都会用到音频技术,因此在这里收集三个SDK的音频技术需求,开发一个通用的音频模块用于三个SDK ...

  8. 重新想象 Windows 8 Store Apps (24) - 文件系统: Application Data 中的文件操作, Package 中的文件操作, 可移动存储中的文件操作

    原文:重新想象 Windows 8 Store Apps (24) - 文件系统: Application Data 中的文件操作, Package 中的文件操作, 可移动存储中的文件操作 [源码下载 ...

  9. windows下Android利用ant自动编译、修改配置文件、批量多渠道,打包生成apk文件

    原创文章,转载请注明:http://www.cnblogs.com/ycxyyzw/p/4535459.html android 程序打包成apk,如果在是命令行方式,一般都要经过如下步骤: 1.用a ...

随机推荐

  1. 节后复工,Apache DolphinScheduler喜迎7位新Committer

    Apache DolphinScheduler(Incubating)社区在节后上周第一周就迎来了好消息,经过 Apache DolphinScheduler PPMC 们的推荐和投票,我们高兴的宣布 ...

  2. 详解ConCurrentHashMap源码(jdk1.8)

    ConCurrentHashMap是一个支持高并发集合,常用的集合之一,在jdk1.8中ConCurrentHashMap的结构和操作和HashMap都很类似: 数据结构基于数组+链表/红黑树. ge ...

  3. 彩虹女神跃长空,Go语言进阶之Go语言高性能Web框架Iris项目实战-项目入口与路由EP01

    书接上回,我们已经安装好Iris框架,并且构建好了Iris项目,同时配置了fresh自动监控项目的实时编译,万事俱备,只欠东风,彩虹女神蓄势待发.现在我们来看看Iris的基础功能,如何编写项目入口文件 ...

  4. 透过inode来理解硬链接和软链接

    什么是inode? 每个文件都对应一个唯一的inode,inode用来存储文件的元信息,包括: 对应的文件 文件字节数 文件数据块的位置 文件的inode号码 文件的硬链接数 文件的读写权限 文件的时 ...

  5. Nodemon 如何实时监听 TypeScript 项目下的文件并热部署?

    首先你的项目要安装ts-node和nodemon: npm i -D ts-node nodemon 在package.json文件中配置运行脚本: "dev": "no ...

  6. Excel 运算符(一):算术运算符

    算术运算符用于最基本的加.减.乘.除运算. 运算符 含义 实例 结果 + 加法运算 =2+3 5 - 减法运算 =5-2 3 * 乘法运算 =5*2 10 / 除法运算 =4/2 2 % 百分数 =5 ...

  7. APT 安装 MySQL 提示错误:dpkg: error: dpkg frontend lock is locked by another process

    在安装 MySQL 的时候提示错误: ubuntu@VM-0-6-ubuntu:/opt$ sudo dpkg -i mysql-apt-config_0.8.22-1_all.deb dpkg: e ...

  8. Spring 08: AOP面向切面编程 + 手写AOP框架

    核心解读 AOP:Aspect Oriented Programming,面向切面编程 核心1:将公共的,通用的,重复的代码单独开发,在需要时反织回去 核心2:面向接口编程,即设置接口类型的变量,传入 ...

  9. Docker 拉取Nginx镜像 和运行

    Docker 镜像拉取 docker pull [OPTIONS] NAME[:TAG|@DIGEST] 镜像拉取命令 OPTIONS说明: -a :拉取所有 tagged 镜像 --disable- ...

  10. [CF1538E] Funny Substrings (模拟)

    题面 该场 Div. 3 最"难"的一道题:Funny Substrings O I D \tt OID OID 队长喜欢玩字符串,因为 " O n e I n D a ...