views:

707

answers:

2

I want to detect the current volume for the default audio recording device of the current computer. Is there any API to use or solutions?

I am writing an audio recorder and I want to let the user know the current volume for the default audio recording device before recording, so that we can avoid a no-audio-recorded issue (e.g. end user has audio recording device muted).

If the result could be retrieved in the format of a percentage value (i.e. 0% means mute, and 100% means max volume), it would be great!

I am using VSTS 2008 + C# + .Net 3.5 to write a Windows Forms application.

+1  A: 

The way to do this is to open the default WaveIn device using WaveInOpen and that will get you a waveIn handle. Then you can use the mixer... APIs to select the associated mixer line.

This will be a destination line, and will have some controls (often a mute and a volume). You may be able to set these. However, this is where it gets a little complicated. There are also multiple "sources" associated with a destination (e.g. Microphone, Line In etc). These too can have volume and mute and other custom controls. You may need to experiment a little to find the control you really want to change. I have found it hard to come up with code that works reliably on both Vista and XP (it may actually be to do with your sound card drivers).

I have written managed wrappers for all these functions in NAudio which will get you part of the way. This is roughly what you want to do:

MixerLine mixerLine;
if (waveInHandle != IntPtr.Zero)
{
    mixerLine = new MixerLine(waveInHandle, 0, MixerFlags.WaveInHandle);
}
else
{
    mixerLine = new MixerLine((IntPtr)waveInDeviceNumber, 0, MixerFlags.WaveIn);
}

foreach (MixerControl control in mixerLine.Controls)
{
    if (control.ControlType == MixerControlType.Volume)
    {
        // this is the volume control of the "destination"
        UnsignedMixerControl volumeControl = (UnsignedMixerControl)control;
        Debug.WriteLine(volumeControl.Percent.ToString());
    }      
}

// to examine the volume controls of the "sources":
if (source.ComponentType == MixerLineComponentType.SourceMicrophone)
{
    foreach (MixerControl control in source.Controls)
    {
        if (control.ControlType == MixerControlType.Volume)
        {
            // this might be the one you want to set
        }
    }
}
Mark Heath
+1  A: 

For capture devices, the mixer volume and the endpoint volume both reflect the volume of the actual capture hardware (this lets apps that use AGC work correctly without modification).

Larry Osterman