1

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.

Tom Lenc
  • 765
  • 1
  • 17
  • 41
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Draco18s no longer trusts SE Jan 12 '18 at 02:59
  • Technically, that is not the line of code that's crashing. That's the *call* to the function that contains the line of code that is crashing. – Draco18s no longer trusts SE Jan 12 '18 at 02:59
  • You should Debug your `enumerator` variable. It's possible that a variable that you are trying to use is null and that's why you are getting a NullReferenceException. Since this is the only text you provided us. I'm going to guess it's your `var enumerator`. – Vitor Figueredo Jan 12 '18 at 04:46
  • I'll say this again: `NullPointerException` => JAVA, `NullReferenceException` => .NET. Not sure why your title says Pointer. – Camilo Terevinto Jan 13 '18 at 16:10
  • @CamiloTerevinto sorry, mixed that up while writing the title – Tom Lenc Jan 13 '18 at 16:12

1 Answers1

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.

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120