Get default output audio device with NAudio
Asked Answered
S

1

7

I want to get the default output audio device (i.e. my speakers) using NAudio, to get the master sound volume as in this question.

I am trying to use MMDeviceEnumerator.GetDevice(), but the id it takes is a string, not the device number. Here's the code I've written so far:

        var enumerator = new MMDeviceEnumerator();

        for (int i = 0; i < WaveOut.DeviceCount; i++)
        {
            var cap = WaveOut.GetCapabilities(i);
            Console.WriteLine("{0}: {1}", i, cap.ProductName);

            var device = enumerator.GetDevice(???);
        }

        Console.WriteLine();

        Console.ReadLine();

I've tried passing the various Guids from the capabilities, as well as the device id in string format, to GetDevice() but none of them work.

How do I get the default device?

Snowblink answered 27/9, 2014 at 18:39 Comment(0)
F
13

You are mixing two completely different audio APIs here. MMDeviceEnumerator is part of WASAPI, the new audio API introduced in WindowsVista, and WaveOut.DeviceCount uses the old Windows audio APIs.

To use WASAPI to get the default audio device, you use code like this:

var enumerator = new MMDeviceEnumerator();
enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Console);

There are actually three different types of default audio output device, depending on the purpose (role):

    /// <summary>
    /// Games, system notification sounds, and voice commands.
    /// </summary>
    Console,

    /// <summary>
    /// Music, movies, narration, and live music recording
    /// </summary>
    Multimedia,

    /// <summary>
    /// Voice communications (talking to another person).
    /// </summary>
    Communications,
Fostoria answered 8/10, 2014 at 12:36 Comment(2)
Exactly what I was looking for. You could also just use CoreAudioAPI from NAudio to load less code.Riviera
@Dominique Alexandre how would i do so? In 2018 this MMDeviceEnumerator(); cannot be used I think. VS will not allow it.Dingo

© 2022 - 2024 — McMap. All rights reserved.