Search code examples
c#audionaudio

Show volume peak of default device output


I got code that shows volume peak of selected device. How can i make it to show volume peak without selecting device from ComboBox1?

Here`s my code:

        public Form1()
        {
            InitializeComponent();
            MMDeviceEnumerator enumerator = new MMDeviceEnumerator();
            var devices = enumerator.EnumerateAudioEndPoints(DataFlow.All, DeviceState.Active);
            comboBox1.Items.AddRange(devices.ToArray());   
        }

        private NAudio.Wave.WaveFileReader wave = null;
        private NAudio.Wave.DirectSoundOut output = null;

        private void timer_Tick(object sender, EventArgs e)
        {
                var device = (MMDevice) comboBox1.SelectedItem;
                progressBar1.Value = (int)(Math.Round(device.AudioMeterInformation.MasterPeakValue * 100));
        }



}

Solution

  • I believe you need something like this.

    private void timer_Tick(object sender, EventArgs e)
    {
        MMDevice device = null;
    
        if (comboBox1.SelectedItem != null)
            device = (MMDevice)comboBox1.SelectedItem;
        else
            device = GetDefaultAudioEndpoint();
    
        if (device != null)
            progressBar1.Value = (int)(Math.Round(device.AudioMeterInformation.MasterPeakValue * 100));
        else
            progressBar1.Value = 0;
    }
    
    public MMDevice GetDefaultAudioEndpoint()
    {
        MMDeviceEnumerator enumerator = new MMDeviceEnumerator();
        return enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Console);
    }