Example #1
0
        public void Dispose()
        {
            foreach (var session in _sessions.Values)
            {
                session.SessionEnded  -= OnSessionEnded;
                session.VolumeChanged -= OnSessionVolumeChanged;
                session.Dispose();
            }

            _sessions.Clear();

            _callback.NotifyRecived        -= OnEndpointVolumeChanged;
            _sessionManager.SessionCreated -= OnSessionCreated;

            _endpointVolume?.UnregisterControlChangeNotify(_callback);
            _endpointVolume?.Dispose();
            _endpointVolume = null;
            _callback       = null;

            _sessionManager?.Dispose();
            _sessionManager = null;

            _device?.Dispose();
            _device = null;
        }
 public VolumeControl(AudioEndpointVolume endpointVol)
 {
     getVolume = () => endpointVol.MasterVolumeLevelScalar;
     setVolume = (volume) => endpointVol.MasterVolumeLevelScalar = volume;
     isMuted   = () => endpointVol.Mute;
     setMuted  = (mute) => endpointVol.Mute = mute;
 }
Example #3
0
 public void CanCreateAudioEndpointVolume()
 {
     using (var device = Utils.GetDefaultRenderDevice())
         using (var endpointVolume = AudioEndpointVolume.FromDevice(device))
         {
         }
 }
        /**
         * <summary>WASAPI関係の初期化処理</summary>
         */
        public void initDevice()
        {
            if (deviceEnumerator != null)
            {
                return;
            }
            // https://www.ipentec.com/document/document.aspx?page=csharp-shell-namespace-get-icon-from-file-path

            // get the speakers (1st render + multimedia) device
            deviceEnumerator = MMDeviceEnumerator.GetInstance();

            // set device state notification.
            deviceEnumerator.OnDefaultDeviceChanged += innerListener.OnDefaultDeviceChanged;

            // get default device.
            device = deviceEnumerator.GetDefaultAudioEndpoint(DataFlow, Role);
            if (device == null)
            {
                return;
            }
            volume = device.AudioEndpointVolume;

            // set volume state notification.
            volume.OnVolumeNotification += innerListener.OnVolumeNotify;
        }
        /**
         * <summary>デバイス更新処理。主にデフォルトデバイスの更新があった際に呼ばれる。
         *      対象デバイスにListenerの設定を行う</summary>
         * <remarks><paramref name="deviceId"/>がnull場合、処理を終了する。</remarks>
         * <param name="deviceId">deviceIdから再生デバイスの参照を取得し、内部クラス<see cref="InnerListener"/>への通知設定を行う。</param>
         * <returns>void</returns>
         */
        void updateDevice(string deviceId)
        {
            // イレギュラー時は終了
            if (deviceEnumerator == null || deviceId == null)
            {
                return;
            }

            // defaultでなくなったDeviceの参照を切る
            if (volume != null)
            {
                volume.OnVolumeNotification -= innerListener.OnVolumeNotify;
            }
            // 今までDefaultだったデバイスを開放
            //volume?.Dispose(true);
            //device?.Dispose(true);
            volume = null;
            device = null;

            // 新しくdefaultになったDeviceの参照を得る
            device = deviceEnumerator.GetDevice(deviceId);
            if (device != null)
            {
                volume = device.AudioEndpointVolume;
                var meter = device.AudioMeterInformation;
                volume.OnVolumeNotification += innerListener.OnVolumeNotify;    // volumeに対して変更通知のListenerを設定
            }
        }
Example #6
0
 public void SetVolume(float volume)
 {
     if (sessionType == SessionType.Application)
     {
         foreach (var session in audioSessions)
         {
             session.SimpleAudioVolume.Volume = volume;
         }
     }
     else if (sessionType == SessionType.Master)
     {
         try
         {
             deviceVolume.MasterVolumeLevelScalar = volume;
         }
         catch (System.Runtime.InteropServices.InvalidComObjectException e)
         {
             // This catch handles the "COM object that has been separated from its underlying RCW cannot be used" issue.
             // I believe this happens when we refresh the device when opening the menu, but this is fine for now.
             Console.WriteLine($@"Error when setting master volume: {e.Message}");
             deviceVolume = parent.GetDeviceVolumeObject();
             deviceVolume.MasterVolumeLevelScalar = volume;
             Console.WriteLine($@"RETRY: Setting master volume to {volume}");
         }
     }
 }
Example #7
0
        public void Dispose()
        {
            if (_deviceEnumerator != null)
            {
                _deviceEnumerator.DefaultDeviceChanged -= OnDefaultDeviceChanged;
                _deviceEnumerator.DeviceRemoved        -= OnDeviceRemoved;
                _deviceEnumerator.DeviceStateChanged   -= OnDeviceStateChanged;
            }

            if (_callback != null)
            {
                _callback.NotifyRecived -= OnEndpointVolumeChanged;
            }

            if (_endpointVolume != null)
            {
                _endpointVolume.UnregisterControlChangeNotify(_callback);
            }

            _deviceEnumerator = null;
            _endpointVolume   = null;
            _callback         = null;

            Device = null;
        }
Example #8
0
        public static void Main()
        {
            using (MMDeviceEnumerator enumerator = new MMDeviceEnumerator())
                using (MMDevice device = enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Console))
                    using (AudioEndpointVolume endpointVolume = AudioEndpointVolume.FromDevice(device))
                        using (AudioSessionManager2 sessionManager2 = AudioSessionManager2.FromMMDevice(device))
                            using (AudioSessionEnumerator sessionEnumerator = sessionManager2.GetSessionEnumerator())
                            {
                                Console.WriteLine("Default Render Device: " + device.FriendlyName);
                                Console.WriteLine("Master Volume Scalar: " + endpointVolume.GetMasterVolumeLevelScalar());
                                Console.WriteLine("\nGetting audio sessions...");

                                foreach (AudioSessionControl sessionControl in sessionEnumerator)
                                {
                                    PrintSessionName(sessionControl);
                                    Console.WriteLine("\t- State: " + sessionControl.SessionState.ToString());

                                    using (SimpleAudioVolume sessionSimpleVolume = sessionControl.QueryInterface <SimpleAudioVolume>())
                                    {
                                        Console.WriteLine("\t- Volume: " + sessionSimpleVolume.MasterVolume);
                                        sessionSimpleVolume.MasterVolume = 1.0f;
                                    }

                                    sessionControl.Dispose();
                                }
                            }
            Console.WriteLine("\nVolumes reset!");
            Console.ReadLine();
        }
Example #9
0
        public bool ToggleMute()
        {
            if (sessionType == SessionType.Application)
            {
                var muted = !audioSessions.First().SimpleAudioVolume.Mute;
                foreach (var session in audioSessions)
                {
                    session.SimpleAudioVolume.Mute = muted;
                }
                return(muted);
            }
            else if (sessionType == SessionType.Master)
            {
                try
                {
                    var muted = !deviceVolume.Mute;
                    deviceVolume.Mute = muted;
                    return(muted);
                }
                catch (System.Runtime.InteropServices.InvalidComObjectException e)
                {
                    // This catch handles the "COM object that has been separated from its underlying RCW cannot be used" issue.
                    // I believe this happens when we refresh the device when opening the menu, but this is fine for now.
                    Console.WriteLine($@"Error when toggling mute on master volume: {e.Message}");
                    deviceVolume = parent.GetDeviceVolumeObject();
                    var muted = !deviceVolume.Mute;
                    deviceVolume.Mute = muted;

                    Console.WriteLine("RETRY: toggling mute on master volume");
                    return(muted);
                }
            }
            return(false);
        }
Example #10
0
        private void updateDeviceInfoImpl(bool needStop)
        {
            if (needStop)
            {
                stopCaptureImpl();
            }
            lock (_lockObj) {
                _deviceInfos.Clear();
                if (_devices != null)
                {
                    foreach (MMDevice device in _devices.EnumerateAudioEndPoints(EDataFlow.eAll, EDeviceState.DEVICE_STATE_ACTIVE))
                    {
                        AudioEndpointVolume vol  = device.AudioEndpointVolume;
                        DeviceInfo          info = new DeviceInfo(device.Id, device.FriendlyName, device.DataFlow, device.State);
                        _deviceInfos.Add(info);
                    }
                }
            }

            // イベント発火
            DeviceInfoUpdatedEventHandler del = DeviceInfoUpdated;

            if (del != null)
            {
                List <DeviceInfo> info = this.DeviceInfos;
                del.Invoke(this, new DeviceInfoUpdatedEventArgs(info));
            }
        }
        public void CreateDevice(EventHandler <DefaultDeviceChangedEventArgs> aDefaultDeviceChangedHandler,
                                 EventHandler <AudioEndpointVolumeCallbackEventArgs> aVolumeChangedHandler)
        {
            try
            {
                //Create device and register default device change notification
                _mMdeviceEnumerator           = new MMDeviceEnumerator();
                iMultiMediaNotificationClient = new MMNotificationClient(_mMdeviceEnumerator);
                iMultiMediaNotificationClient.DefaultDeviceChanged += iDefaultDeviceChangedHandler = aDefaultDeviceChangedHandler;
                var mMdeviceList = _mMdeviceEnumerator.EnumAudioEndpoints(DataFlow.Render, DeviceState.Active);

                if (mMdeviceList != null && mMdeviceList.Count > 0)
                {
                    _mMdevice = _mMdeviceEnumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
                    GUIGraphicsContext.CurrentAudioRendererDevice = _mMdevice.FriendlyName;

                    //Register to get volume modifications
                    if (_mMdevice != null)
                    {
                        iAudioEndpointVolume = AudioEndpointVolume.FromDevice(_mMdevice);
                    }
                    iAudioEndpointVolumeMixerCallback = new CSCore.CoreAudioAPI.AudioEndpointVolumeCallback();
                    iAudioEndpointVolumeMixerCallback.NotifyRecived += iVolumeChangedHandler = aVolumeChangedHandler;
                    iAudioEndpointVolume?.RegisterControlChangeNotify(iAudioEndpointVolumeMixerCallback);
                }

                // For audio session
                Stop();
                //DispatchingTimerStart(); // Disable because the check will be done in IsMuted code
            }
            catch (Exception)
            {
                // When no device available
            }
        }
Example #12
0
        public void Dispose()
        {
            try
            {
                // Do unregistration, can throw
                if (_deviceEnumerator != null)
                {
                    _deviceEnumerator.DefaultDeviceChanged -= OnDefaultDeviceChanged;
                    _deviceEnumerator.DeviceRemoved        -= OnDeviceRemoved;
                    _deviceEnumerator.DeviceStateChanged   -= OnDeviceStateChanged;
                }
                if (_callback != null)
                {
                    _callback.NotifyRecived -= OnEndpointVolumeChanged;
                }
                if (_endpointVolume != null)
                {
                    _endpointVolume.UnregisterControlChangeNotify(_callback);
                }
            }
            catch { }

            // Do disposal chains, each can throw
            try { _deviceEnumerator.Dispose(); }
            catch { }
            try { Device.Dispose(); }
            catch { }

            // Set to null
            _deviceEnumerator = null;
            _endpointVolume   = null;
            _callback         = null;
            Device            = null;
        }
Example #13
0
        public WindowsAudio()
        {
            var device = new MMDeviceEnumerator().GetDefaultAudioEndpoint(DataFlow.Render, Role.Console);

            _volume = AudioEndpointVolume.FromDevice(device);
            _meter  = AudioMeterInformation.FromDevice(device);
        }
 private void OnAudioDeviceChanged(object sender, AudioDeviceChangedEventArgs e)
 {
     if (e.DefaultPlayback != null)
     {
         _endPointVolume = AudioEndpointVolume.FromDevice(e.DefaultPlayback);
     }
 }
Example #15
0
        public AudioSessionVolumeManagerCS()
        {
            InitializeComponent();

            //intialize audio stuff
            var deviceEnumerator = new MMDeviceEnumerator();

            device       = deviceEnumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
            masterVolume = device.AudioEndpointVolume;
            updateMasterVolumeSlider();
            masterVolume.OnVolumeNotification += endpointVolumeNotification;

            //add the session volumes to the list
            updateSessions();
            device.AudioSessionManager.OnSessionCreated += sessionCreatedNotificaton;

            //intialize serial stuff
            string portName;

            foreach (string s in SerialPort.GetPortNames())
            {
                //Debug.WriteLine(s);
                ComSelector.Items.Add(s);
            }
            //readThread = new Thread(read);
            //port = new SerialPort("COM7", 9600, Parity.None, 8, StopBits.One);
            //port.Open();
            //serialRead = true;
            //readThread.Start();
        }
Example #16
0
        public VlcMediaPlayer(IMediaPlayerFactory factory = null, AudioEndpointVolume audioEndpointVolume = null)
        {
            // create the player using the injected factory
            _factory             = factory ?? new MediaPlayerFactory();
            _player              = _factory.CreatePlayer <IVideoPlayer>();
            _audioEndpointVolume = audioEndpointVolume;

            // set default values
            OpenTimeOut    = TimeSpan.FromSeconds(10);
            Async          = true;
            Error          = AudioError.NoError;
            AudioSelection = AudioSelection.Empty;

            // cached event handler to avoid leaks during add and remove
            _durationChanged = (s, e) => OnDurationChanged(e.NewDuration);
            _parsedChanged   = (s, e) => OnParsedChanged();

            // hook events
            _player.Events.MediaChanged           += (s, e) => OnMediaChanged();
            _player.Events.MediaEnded             += (s, e) => OnMediaEnded();
            _player.Events.PlayerEncounteredError += (s, e) => OnEncounteredError();
            _player.Events.PlayerLengthChanged    += (s, e) => OnDurationChanged(e.NewLength);
            _player.Events.PlayerPaused           += (s, e) => OnPaused();
            _player.Events.PlayerPlaying          += (s, e) => OnPlaying();
            _player.Events.PlayerPositionChanged  += (s, e) => OnPositionChanged(e.NewPosition * Duration);
            _player.Events.PlayerPositionChanged  += (s, e) => OnPositionChangedLoop(e.NewPosition);
            _player.Events.PlayerStopped          += (s, e) => OnStopped();
        }
Example #17
0
        private void GetAudioEndpointVolume()
        {
            object result;

            Marshal.ThrowExceptionForHR(deviceInterface.Activate(ref IID_IAudioEndpointVolume, ClsCtx.All, IntPtr.Zero, out result));
            _audioEndpointVolume = new AudioEndpointVolume(result as IAudioEndpointVolume);
        }
Example #18
0
        // Helpers
        private bool GetSetMute(bool Get = true, bool mute = false)
        {
            lock (locker)
            {
                try
                {
                    for (int i = 0; i < deviceInit.AudioSessionManager.Sessions.Count; i++)
                    {
                        AudioSessionControl session = deviceInit.AudioSessionManager.Sessions[i];
                        if (processId == session.GetProcessID)
                        {
                            deviceVol = device.AudioEndpointVolume;

                            if (Get)
                            {
                                return(session.SimpleAudioVolume.Mute | deviceVol.Mute);
                            }
                            session.SimpleAudioVolume.Mute = mute;
                            if (deviceVol.Mute)
                            {
                                deviceVol.Mute = false;
                            }

                            break;
                        }
                    }
                } catch (Exception) { }
            }

            return(false);
        }
Example #19
0
 /// <summary>
 /// Dispose
 /// </summary>
 public void Dispose()
 {
     this._audioEndpointVolume?.Dispose();
     this._audioEndpointVolume = null;
     //this.audioSessionManager?.Dispose();
     GC.SuppressFinalize(this);
 }
Example #20
0
 public SysVolumeConfigurator() // Объявление
 {
     using (var enumerator = new MMDeviceEnumerator())
     {
         device = enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Console);
     }
     endpointVolume = AudioEndpointVolume.FromDevice(device);
 }
Example #21
0
 public CsCoreEngine()
 {
     using (var enumerator = new MMDeviceEnumerator())
     {
         device = enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Console);
     }
     endpointVolume = AudioEndpointVolume.FromDevice(device);
 }
Example #22
0
 public void CanGetAudioEndpointVolumeChannelCount()
 {
     using (var device = Utils.GetDefaultRenderDevice())
         using (var endpointVolume = AudioEndpointVolume.FromDevice(device))
         {
             Debug.WriteLine(endpointVolume.GetChannelCount());
         }
 }
Example #23
0
 public MixerSession(AudioDevice audioDev, string labl, SessionType sesType, AudioEndpointVolume devVol)
 {
     parent            = audioDev;
     label             = labl;
     sessionIdentifier = "";
     audioSessions     = new List <AudioSessionControl>();
     sessionType       = sesType;
     deviceVolume      = devVol;
 }
Example #24
0
        private void UpdateDevice()
        {
            // Add audio devices to each fader menu items
            var deviceEnumerator = new MMDeviceEnumerator();

            device = deviceEnumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
            device.AudioSessionManager.OnSessionCreated += OnSessionCreated;
            deviceVolume = device.AudioEndpointVolume;
        }
Example #25
0
        public MaximumVolume()
        {
            var enumator = new MMDeviceEnumerator();
            var device   = enumator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);

            volumeControl = device.AudioEndpointVolume;

            maximizeVolume();
        }
Example #26
0
        /// <summary>
        /// Gets the ratio of volume across the left and right speakers in a range between -1 (left) and 1 (right). The default is 0 (center).
        /// </summary>
        /// <param name="volume">The audio volume endpoint</param>
        /// <returns></returns>
        public static float GetBalance(this AudioEndpointVolume volume)
        {
            VerifyChannels(volume);
            var masterVol = Math.Max(1e-6f, volume.MasterVolumeLevelScalar);
            var leftVol   = volume.Channels[LeftChan].VolumeLevelScalar;
            var rightVol  = volume.Channels[RightChan].VolumeLevelScalar;
            var balance   = (rightVol - leftVol) / masterVol;

            return(balance);
        }
Example #27
0
 private static AudioEndpointVolume GetDefaultAudioEndpointVolume()
 {
     using (var enumerator = new MMDeviceEnumerator())
     {
         using (var device = enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia))
         {
             return(AudioEndpointVolume.FromDevice(device));
         }
     }
 }
Example #28
0
        public static void SetBalance(this AudioEndpointVolume volume, float balance)
        {
            var safeBalance = Math.Max(-1, Math.Min(1, balance));
            var masterVol   = volume.MasterVolumeLevelScalar;
            var rightVol    = 1f + Math.Min(0f, safeBalance);
            var leftVol     = 1f - Math.Max(0f, safeBalance);

            volume.Channels[LeftChan].VolumeLevelScalar  = leftVol * masterVol;
            volume.Channels[RightChan].VolumeLevelScalar = rightVol * masterVol;
        }
        public static void SetMicMute(bool muted)
        {
            var endpoint = AudioEndpointVolume.FromDevice(microphone);

            if (endpoint.GetMute() != muted)
            {
                endpoint.SetMute(muted, eventguid);
                Plugin.Log.Info($"Microphone muted: {muted}");
            }
        }
Example #30
0
 public void CanGetAudioEndpointVolume()
 {
     using (var device = Utils.GetDefaultRenderDevice())
         using (var endpointVolume = AudioEndpointVolume.FromDevice(device))
         {
             var volume = endpointVolume.GetMasterVolumeLevelScalar();
             Debug.WriteLine("Volume: {0}", volume);
             endpointVolume.SetMasterVolumeLevelScalar(0.5f, Guid.Empty);
         }
 }