windows-audio-sync/AudioManager/AudioManager.cpp

113 lines
2.7 KiB
C++
Raw Normal View History

2022-12-28 16:52:42 +00:00
// AudioManager.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <windows.h>
#include <commctrl.h>
#include <mmdeviceapi.h>
#include <endpointvolume.h>
#include "CAudioEndpointVolumeCallback.h"
#define EXIT_ON_ERROR(hr) \
if (FAILED(hr)) { exit(-1); }
#define ERROR_CANCEL(hr) \
if (FAILED(hr)) { \
MessageBox(hDlg, TEXT("The program will exit."), \
TEXT("Fatal error"), MB_OK); \
EndDialog(hDlg, TRUE); return TRUE; }
#define SAFE_RELEASE(punk) \
if ((punk) != NULL) \
{ (punk)->Release(); (punk) = NULL; }
volatile bool isRunning = true;
BOOL WINAPI HandlerRoutine(_In_ DWORD dwCtrlType) {
switch (dwCtrlType)
{
case CTRL_C_EVENT:
isRunning = false;
// Signal is handled - don't pass it on to the next handler
return TRUE;
default:
// Pass signal on to the next handler
return FALSE;
}
}
int main()
{
HRESULT hr = S_OK;
GUID g_guidMyContext = GUID_NULL;
IMMDeviceEnumerator* pEnumerator = NULL;
IMMDevice* pDevice = NULL;
IMMDevice* cDevice = NULL;
static IAudioEndpointVolume* g_pEndptVol = NULL;
static IAudioEndpointVolume* g_cEndptVol = NULL;
SetConsoleCtrlHandler(HandlerRoutine, TRUE);
hr = CoInitialize(NULL);
EXIT_ON_ERROR(hr);
hr = CoCreateGuid(&g_guidMyContext);
EXIT_ON_ERROR(hr);
// Get enumerator for audio endpoint devices.
hr = CoCreateInstance(__uuidof(MMDeviceEnumerator),
NULL, CLSCTX_INPROC_SERVER,
__uuidof(IMMDeviceEnumerator),
(void**)&pEnumerator);
EXIT_ON_ERROR(hr);
hr = pEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &pDevice);
EXIT_ON_ERROR(hr);
hr = pEnumerator->GetDefaultAudioEndpoint(eRender, eCommunications, &cDevice);
EXIT_ON_ERROR(hr);
hr = pDevice->Activate(__uuidof(IAudioEndpointVolume),
CLSCTX_ALL, NULL, (void**)&g_pEndptVol);
EXIT_ON_ERROR(hr);
hr = cDevice->Activate(__uuidof(IAudioEndpointVolume),
CLSCTX_ALL, NULL, (void**)&g_cEndptVol);
EXIT_ON_ERROR(hr);
CAudioEndpointVolumeCallback EPVolEvents(g_pEndptVol, g_cEndptVol, g_guidMyContext);
float mainVolume;
hr = g_pEndptVol->GetMasterVolumeLevelScalar(&mainVolume);
EXIT_ON_ERROR(hr);
float commVolume;
hr = g_cEndptVol->GetMasterVolumeLevelScalar(&commVolume);
EXIT_ON_ERROR(hr);
std::cout << "\r\033[2KMain Volume : " << mainVolume * 100 << ", Communication Volume : " << commVolume * 100;
hr = g_pEndptVol->RegisterControlChangeNotify(
(IAudioEndpointVolumeCallback*)&EPVolEvents);
EXIT_ON_ERROR(hr);
while (isRunning) {
Sleep(0);
}
SAFE_RELEASE(pEnumerator);
SAFE_RELEASE(pDevice);
SAFE_RELEASE(g_pEndptVol);
SAFE_RELEASE(g_cEndptVol);
CoUninitialize();
return 0;
}