I’m trying to use the NAudio library in a Unity3D project. When calling MMDeviceEnumerator.EnumerateAudioEndPoints, a NullReferenceException is thrown. This does not occur in a Visual Studio project targeting .NET 2.0. The enumerator itself is not null. That method wraps a call to IMMDeviceEnumerator.EnumAudioEndpoints, which is what’s directly throwing this exception (I moved a bunch of code from NAudio into my Unity3D project).
The only real difference here is that it’s running inside a Unity3D game, rather than a standard Visual Studio application. What could be causing this? Please help.
Update:
My code that throws (second line):
MMDeviceEnumerator enumerator = new MMDeviceEnumerator();
MMDeviceCollection collection = enumerator.EnumerateAudioEndPoints(DataFlow.All, DeviceState.All);
NAudio code that throws (second line of method):
public MMDeviceCollection EnumerateAudioEndPoints(DataFlow dataFlow, DeviceState dwStateMask)
{
IMMDeviceCollection result;
Marshal.ThrowExceptionForHR(_realEnumerator.EnumAudioEndpoints(dataFlow, dwStateMask, out result));
return new MMDeviceCollection(result);
}
Update x2:
In the constructor for MMDeviceEnumerator in NAudio:
_realEnumerator = new MMDeviceEnumeratorComObject() as IMMDeviceEnumerator;
The new com object is not null, but when casting, it becomes null. Again, this works in a Visual Studio project, but not Unity3D. Here’s the definitions of each (from the NAudio source):
[ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")]
class MMDeviceEnumeratorComObject
{
}
and
[Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMMDeviceEnumerator
{
int EnumAudioEndpoints(DataFlow dataFlow, DeviceState stateMask,
out IMMDeviceCollection devices);
int GetDefaultAudioEndpoint(DataFlow dataFlow, Role role, out IMMDevice endpoint);
int GetDevice(string id, out IMMDevice deviceName);
int RegisterEndpointNotificationCallback(IMMNotificationClient client);
int UnregisterEndpointNotificationCallback(IMMNotificationClient client);
}
I can post the other objects in there if necessary. What I’m missing is probably the core “why” something between Unity3D (also targeting .NET 2.0) and Visual Studio would change.