Search code examples
c++windows-10wasapi

How do I use get access to audio devices through the MMDevice API?


I am trying to manage the audio streams with a program, but I am having trouble even getting access to an audio device. As a side note I am new to C++ and I learned coding in Java so I'm new to the idea of pointers as well as the ideas of the HRESULT and other windows stuff. On this page it says that I must first enumerate an audio endpoint device. I then did some more searching to find out how to do so and was lead to the Enumerating Audio Devices page. That page told me to use the MMDevice API. This page shows this code:

const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator);
const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator);
hr = CoCreateInstance(
     CLSID_MMDeviceEnumerator, NULL,
     CLSCTX_ALL, IID_IMMDeviceEnumerator,
     (void**)&pEnumerator);

I tried to use this and the

(void**)&pEnumerator

did not work, so I found some other code that used a

reinterpret_cast<>();

in order to deal with this error. But the problem that I am running into is that I am not getting a pointer. My code is below.

CoInitializeEx(NULL, COINIT_MULTITHREADED);

IMMDeviceEnumerator *pEnumerator;

const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator);
const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator);

//print CLSID to see if I get any ids
std::cout << CLSID_MMDeviceEnumerator.Data1 << "\n";
std::cout << CLSID_MMDeviceEnumerator.Data2 << "\n";
std::cout << CLSID_MMDeviceEnumerator.Data3 << "\n";
std::cout << CLSID_MMDeviceEnumerator.Data4 << "\n";

//temp variable to hold the result of the CoCreateInstance call
LPVOID *ppv = NULL;

HRESULT retrivedDeviceEnumerator = CoCreateInstance(
    CLSID_MMDeviceEnumerator,
    NULL,
    CLSCTX_ALL,
    IID_IMMDeviceEnumerator,
    ppv
);
//I'm sure there is a better way to print and end the line
//print mem location to see if I am getting a result
std::cout << ppv << "\n";
//cast the result to correct type
pEnumerator = (reinterpret_cast<IMMDeviceEnumerator*>(ppv));

This code prints some numbers for the CLSID lines so I think that those are getting the correct values, but I am getting 00000000 when I print the ppv pointer.


Solution

  • Relatively good code snippet from there:

    CoInitialize(NULL);
    IMMDeviceEnumerator *deviceEnumerator = NULL;
    hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_INPROC_SERVER, 
        __uuidof(IMMDeviceEnumerator), (LPVOID *)&deviceEnumerator);
    IMMDevice *defaultDevice = NULL;
    hr = deviceEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &defaultDevice);
    ...