C# Unity 3D NAudio throws NullReferenceException while checking for default audio endpoint

白昼怎懂夜的黑 提交于 2020-01-05 13:13:48

问题


I've just installed Unity 3D because I wanted to make a simple game. There is one problem with the NAudio library though.

This is my code:

var enumerator = new MMDeviceEnumerator();

if (enumerator.HasDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia)) //<--- crashes here
{
   //...
}

This is literally all Unity says when trying to launch the game:

NullReferenceException: Object reference not set to an instance of an object NAudio.CoreAudioApi.MMDeviceEnumerator.HasDefaultAudioEndpoint (DataFlow dataFlow, Role role)

I don't understand why it throws this kind of error here. Could it be that the library might not be compatible with this version of net framework (version 3.5)?

EDIT: the variable enumerator can't be null, so stop flagging this post as a duplicate of 'What is a NullReferenceException, and how do I fix it?'

I've also tried using this libary: https://code.google.com/archive/p/naudio-with-unity3d/downloads That library only doesn't contain the HasDefaultAudioEndpoint() function, so I just tried getting the audio endpoint directly by calling GetDefaultAudioEndpoint() but it still threw that same error on that line.


回答1:


The problem is not your code. If you look at the source code for HasDefaultAudioEndpoint, it looks like this:

public bool HasDefaultAudioEndpoint(DataFlow dataFlow, Role role)
{
    IMMDevice device = null;
    int hresult = ((IMMDeviceEnumerator)realEnumerator).GetDefaultAudioEndpoint(dataFlow, role, out device);
    ...
}

Where realEnumerator is:

[ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")]
class MMDeviceEnumeratorComObject
{
}

It's not checking whether realEnumerator != null, most likely because Unity was not considered and it doesn't support some COM+ interop.

If you look at this question from 2012, 4 years later the OP answered it never worked, and had to create a c++ DLL for this.



来源:https://stackoverflow.com/questions/48217715/c-sharp-unity-3d-naudio-throws-nullreferenceexception-while-checking-for-default

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!