0

I'm using the Windows Core Audio API, with a wrapper from Controlling Application's Volume: By Process-ID

In this test method here, which sets the volume of a application (by ProcessID):

[TestMethod]
public void CanChangeVolume()
{
    VolumeMixer.SetApplicationVolume(19348, 50f);
}

If i manually enter 19348 into the code, the function works as it should.

But if i pass a dynamic value, like so...

[TestMethod]
public void CanChangeVolume()
{
    foreach (AudioSession session in AudioUtilities.GetAllSessions())
    {
        if (session.Process != null)
        {
            VolumeMixer.SetApplicationVolume(session.ProcessId, 50f);
        }
    }
}

... i get the following error by the Core Audio API:

System.InvalidCastException: Unable to cast object of type 'MMDeviceEnumerator' to type 'RemoteVolume.Server.MMDeviceEnumerator'.

Note: Printing out session.ProcessId is also working fine...

For Example: session.ProcessId = 8508, VolumeMixer.SetApplicationVolume(8508, 50f) is working fine

Christoph Pader
  • 158
  • 3
  • 13
  • 1
    Can you step through both of your test functions with the debugger, and step in to the execution of `SetApplicationVolume` for each one to see exactly where the failure is occurring? I'm wondering if the first test succeeds because `19348` is not a valid process ID and it's bypassing the bad cast within `SetApplicationVolume`. – ozeanix Jun 11 '17 at 19:37
  • @ozeanix and the test function doesn't only succeed because of a invalid processID, it actually changes the volume... – Christoph Pader Jun 11 '17 at 19:47
  • 1
    Well, you're failing on the line where you're casting the `new MMDeviceEnumerator()` to `IMMDeviceEnumerator`, but that's not necessarily happening in C++ code. That could be because `MMDeviceEnumerator` and `IMMDeviceEnumerator` both need the `[ComVisible]` attribute applied to them, and the interface doesn't have it. I'm curious how it works in the first case and not in the second, though, because it should fail both times. Also, when you specify the hardcoded process ID, is there actually a process for it, or is the system master volume changing? – ozeanix Jun 11 '17 at 19:55
  • @ozeanix you're right it's failing at casting from `MMDeviceEnumerator` to `IMMDeviceEnumerator`, but funnily enough, it's working hardcoded. And yes, the applications volume is actually changing. – Christoph Pader Jun 11 '17 at 20:05
  • @ozeanix `[ComVisible(true)]` doesn't work for me... – Christoph Pader Jun 11 '17 at 20:08
  • @ozeanix I actually managed to do the same by just using the Windows Core Audio API in a seperate C++ Project... but thanks for your help :-) – Christoph Pader Jun 11 '17 at 21:49
  • 1
    I suppose that proves it's some kind of .NET COM interop problem since it works fine in C++! Glad you got it working. – ozeanix Jun 11 '17 at 23:50

0 Answers0