2

У меня есть потребность управлять громкостью микрофона, а так же выключать и включать его.

Подскажите, какие есть API для управления аудиоустройствами в Windows? Если есть библиотеки для .net - будет вообще хорошо.

Поиск по https://docs.microsoft.com/ выдаёт только команды жестов для WPF.

0

2 ответа 2

2

Без сторонних библиотек это можно сделать с помощью IAudioEndpointVolume. Вот пример, основанный на ответе участника Simon Mourier со Stackoverflow.com:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace ConsoleApp1
{
    class Program
    {
        //Объявления COM Interop для Core Audio API 

        [ComImport]
        [Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")]
        internal class MMDeviceEnumerator
        {
        }

        internal enum EDataFlow
        {
            eRender,
            eCapture,
            eAll,
            EDataFlow_enum_count
        }

        internal enum ERole
        {
            eConsole,
            eMultimedia,
            eCommunications,
            ERole_enum_count
        }

        [ComImport]
        [Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        internal interface IMMDeviceEnumerator
        {
            int NotImpl1();

            [PreserveSig]
            int GetDefaultAudioEndpoint(EDataFlow dataFlow, ERole role, out IMMDevice ppDevice);

            // the rest is not implemented
        }

        [ComImport]
        [Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        internal interface IMMDevice
        {
            [PreserveSig]
            int Activate(ref Guid iid, int dwClsCtx, IntPtr pActivationParams, [MarshalAs(UnmanagedType.IUnknown)] out object ppInterface);

            // the rest is not implemented
        }

        [ComImport]
        [Guid("5CDF2C82-841E-4546-9722-0CF74078229A"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        internal interface IAudioEndpointVolume
        {
            void A();

            void B();

            void C();

            void SetMasterVolumeLevel(float level,[MarshalAs(UnmanagedType.LPStruct)] Guid eventContext);

            void SetMasterVolumeLevelScalar(float level, [MarshalAs(UnmanagedType.LPStruct)] Guid eventContext);
                        
            float GetMasterVolumeLevel();
                        
            float GetMasterVolumeLevelScalar();

            void SetChannelVolumeLevel(uint channelNumber, float level,[MarshalAs(UnmanagedType.LPStruct)] Guid eventContext);

            void SetChannelVolumeLevelScalar(uint channelNumber,float level,[MarshalAs(UnmanagedType.LPStruct)] Guid eventContext);

            void GetChannelVolumeLevel( uint channelNumber, out float level);
                        
            float GetChannelVolumeLevelScalar(uint channelNumber);

            void SetMute([MarshalAs(UnmanagedType.Bool)] bool isMuted,[MarshalAs(UnmanagedType.LPStruct)] Guid eventContext);

            [return: MarshalAs(UnmanagedType.Bool)] bool GetMute();

            // the rest is not implemented
        }

        static void SafeRelease<T>(ref T ptr) where T:class
        {
            if (ptr != null)
            {
                Marshal.ReleaseComObject(ptr);
                ptr = null;
            }
        }

        private static void SetVolume(float newvalue) //задаем громкость микрофона по умолчанию
        {
            IMMDeviceEnumerator deviceEnumerator = null;
            IMMDevice micro = null;
            IAudioEndpointVolume vol = null;
            Guid IID_IAudioEndpointVolume = typeof(IAudioEndpointVolume).GUID;
            object o;

            try
            {                
                deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
                deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eCapture, ERole.eMultimedia, out micro);
                
                micro.Activate(ref IID_IAudioEndpointVolume, 0, IntPtr.Zero, out o);
                vol = (IAudioEndpointVolume)o;
                vol.SetMasterVolumeLevel(newvalue, new Guid());                
            }
            finally
            {
                SafeRelease(ref vol);
                SafeRelease(ref micro);
                SafeRelease(ref deviceEnumerator);
            }
        }

        static void Main(string[] args)
        {
            SetVolume(2);
            Console.Read();
        }
    }
}
1

Для управления аудио девайсами в Windows существует MMDevice API (The Windows Multimedia Device). Для записи звука - WASAPI (Windows Audio Session API). (это для справки)

Для .net существует библиотека NAudio.

Получить список аудио устройств ввода:

using NAudio.Wave;
...
for (int deviceIndex = 0; deviceIndex < NAudio.Wave.WaveIn.DeviceCount; deviceIndex++)
{
  var device = WaveIn.GetCapabilities(deviceIndex);
}

Замьютить микрофон:

  var waveInEvent = new NAudio.Wave.WaveInEvent();

  //получить миксер аудио устройства ввода по умолчанию
  var mixer = waveInEvent.GetMixerLine();
  var muteControl = mixer.Controls.FirstOrDefault(x => x.ControlType == NAudio.Mixer.MixerControlType.Mute) as BooleanMixerControl;

  //mute
  muteControl.Value = true;

  //unmute
  muteControl.Value = false;

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.