On a recent home improvement project I needed to be able to manipulate the master volume on my Windows PC.
In the same project I had previously relied on a simple solution by issuing WM_APPCOMMANDs to the operating system to control the volume and mute state of the sound. This is the same API that most peripherals use, such as keyboards with volume buttons.
This approach works reasonably well but has two major drawbacks
You cannot read the current volume setting.
The step sizes when incrementing/decrementing volume are so small that multiple messages are needed to achieve a reasonable volume increase each time the user presses a up/down key.
Windows Audio APIs
So I wanted to be able to read the current master volume level on my box and increment/decrement this same master volume in custom step sizes. To solve this I experimented with a few different APIs that are offered by the Windows OS.
Multimedia functions (Winmm.dll)
Although this API is quite mature and widely supported by Windows, I must admit that I didn't have any real luck with integrating them into a C# app. The multimedia waveXxx functions in the Winmm.dll library have been supported by Windows since Win2k but invoking and using them is both complicated and error prone.
For my use I found them an overkill as I wasn't really interested in multi channel sound control when I just wanted to raise and decrease the volume uniformly and not worry about the left and right channels independently.
Core Audio API
As I am only interested in supporting Win7 and newer I luckily found a newer library that was introduced in Windows Vista, the Windows Core Audio APIs.. They are actually a lower level API than the multimedia functions discussed above but I found them much easier to work with.
The benefit of this API is that you can very easily control both the master volume of the operating system as well as each individual application volume. This API is also conveniently accessible using COM interop.
I found a few articles on-line about how to instantiate and manipulate this API using C# and P/Invoke. The biggest help was the .NET Core Audio APIs library that provided me with conveniently pre-abstracted COM interfaces for the CoreAPI functions. Neat!
Using that I assembled the bare minimum needed to manipulate the master and each individual app audio levels and mute state into an AudioManager class.
An example integration of this class can be found in my Netflix remote control example project for the Xbox Big Button Controllers.
Developer & Programmer with +15 years professional experience building software.
Seeking WFH, remoting or freelance opportunities.