Example #1
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                // free managed resources
                if (soundInSource != null)
                {
                    soundInSource.Dispose();
                    soundInSource = null;
                }

                if (mMDeviceEnumerator != null)
                {
                    mMDeviceEnumerator.Dispose();
                    mMDeviceEnumerator = null;
                }

                if (mMNotificationClient != null)
                {
                    mMNotificationClient.Dispose();
                    mMNotificationClient = null;
                }

                if (_soundIn != null)
                {
                    _soundIn.Dispose();
                    _soundIn = null;
                }
            }
        }
Example #2
0
 public CsCoreModule()
 {
     mMNotificationClient = new MMNotificationClient();
     mMDeviceEnumerator   = new MMDeviceEnumerator();
     mMDeviceEnumerator.RegisterEndpointNotificationCallback(mMNotificationClient);
     mMNotificationClient.DefaultDeviceChanged += MMNotificationClient_DefaultDeviceChanged;
 }
        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 #4
0
 /// <summary>
 /// The Constructor
 /// </summary>
 public AudioDeviceController()
 {
     _deviceEnumerator   = MMDeviceEnumeratorFactory.CreateInstance();
     _deviceNotification = new MMNotificationClient();
     _deviceEnumerator.RegisterEndpointNotificationCallback(_deviceNotification);
     _deviceNotification.RegisterAudioDeviceStateChange(OnAudioDeviceChange);
 }
        private void InitializeAudio(AudioDataFlow audioFlow, IMMDeviceEnumerator deviceEnumerator)
        {
            //Get Audio Device
            COMResult result = deviceEnumerator.GetDefaultAudioEndpoint(audioFlow, EndPointRole.eMultimedia, out _audioDevice);

            //Register End point notification
            _notifyClient = new MMNotificationClient();
            result        = deviceEnumerator.RegisterEndpointNotificationCallback(_notifyClient);
            //Get Audio Client from device
            result       = _audioDevice.Activate(typeof(IAudioClient).GUID, 0, IntPtr.Zero, out object obj);
            _audioClient = (IAudioClient)obj;
            //Get Audio Meter from device
            result      = _audioDevice.Activate(typeof(IAudioMeterInformation).GUID, 0, IntPtr.Zero, out obj);
            _audioMeter = (IAudioMeterInformation)obj;
            //Initialize Audio Client.
            _sessionGuid = new Guid();
            result       = _audioClient.GetMixFormat(out waveFormat);
            AudioClientStreamFlags streamFlag = AudioClientStreamFlags.None;

            if (audioFlow == AudioDataFlow.eRender)
            {
                streamFlag = AudioClientStreamFlags.Loopback;
            }
            result = _audioClient.Initialize(AudioClientMode.Shared, streamFlag, 10000000, 0, waveFormat, ref _sessionGuid);
            //Get Capture Client.
            result = _audioClient.GetService(typeof(IAudioCaptureClient).GUID, out obj);
            Marshal.ThrowExceptionForHR((int)result);
            _audioCaptureClient = (IAudioCaptureClient)obj;
            result = _audioClient.Start();
            //Change wave format here
            SetupWaveFormat(waveFormat);
        }
Example #6
0
 public CSCoreSoundOutProvider()
 {
     _mmNotificationClient = new MMNotificationClient();
     SoundOutModes         = new ObservableCollection <ISoundOutMode>();
     LoadSoundOutModes();
     LoadEvents();
 }
Example #7
0
 private void MMnotify()
 {
     if (MMN == null)
     {
         MMN = new CSCore.CoreAudioAPI.MMNotificationClient();
     }
     MMN.DefaultDeviceChanged += CoreTestMainWindow_DefaultDeviceChanged;
     MMN.DeviceStateChanged   += Mmn_DeviceStateChanged;
 }
        /// <summary>
        /// Creates a new MM Device Enumerator
        /// </summary>
        public MMDeviceEnumerator()
        {
            if (Environment.OSVersion.Version.Major < 6)
            {
                throw new NotSupportedException("This functionality is only supported on Windows Vista or newer.");
            }
            _realEnumerator = new MMDeviceEnumeratorComObject() as IMMDeviceEnumerator;

            _notificationClient = new MMNotificationClient(this);
        }
Example #9
0
        private void CloseNotificationClient()
        {
            if (this.MMNotificationClient != null)
            {
                this.MMNotificationClient.DefaultDeviceChanged -= MMNotificationClient_DefaultDeviceChanged;

                this.MMNotificationClient.Dispose();
                this.MMNotificationClient = null;
            }
        }
Example #10
0
        public MainViewModel()
        {
            _deviceEnumerator                          = new MMDeviceEnumerator();
            _notificationClient                        = new MMNotificationClient(_deviceEnumerator);
            _notificationClient.DeviceAdded           += (s, e) => UpdateDevices();
            _notificationClient.DeviceRemoved         += (s, e) => UpdateDevices();
            _notificationClient.DevicePropertyChanged += (s, e) => UpdateDevices();

            UpdateDevices();
        }
Example #11
0
 public void CanCreateDeviceNotificationEvent()
 {
     using (var enumerator = new MMDeviceEnumerator())
         using (var notification = new MMNotificationClient(enumerator))
         {
             notification.DefaultDeviceChanged  += (s, e) => { };
             notification.DeviceAdded           += (s, e) => { };
             notification.DevicePropertyChanged += (s, e) => { };
             notification.DeviceRemoved         += (s, e) => { };
             notification.DeviceStateChanged    += (s, e) => { };
         }
 }
Example #12
0
 /// <summary>
 /// Set MMnotification events
 /// </summary>
 private void MMnotify()
 {
     M.D(100, "MMnotify");
     if (MMN == null)
     {
         MMN = new CSCore.CoreAudioAPI.MMNotificationClient();
     }
     MMN.DefaultDeviceChanged += MMN_DefaultDeviceChanged;
     MMN.DeviceStateChanged   += MMN_DeviceStateChanged;
     MMN.DeviceRemoved        += MMN_DeviceRemoved;
     M.D(109);
 }
        /// <summary>
        /// Called to dispose/finalize contained objects.
        /// </summary>
        /// <param name="disposing">True if disposing, false if called from a finalizer.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_notificationClient != null)
                {
                    _notificationClient.Dispose();
                    _notificationClient = null;
                }

                if (_realEnumerator != null)
                {
                    // although GC would do this for us, we want it done now
                    Marshal.ReleaseComObject(_realEnumerator);
                    _realEnumerator = null;
                }
            }
        }
Example #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="aDefaultDeviceChangedHandler"></param>
        /// <param name="aVolumeChangedHandler"></param>
        public void Open(EventHandler <DefaultDeviceChangedEventArgs> aDefaultDeviceChangedHandler,
                         EventHandler <AudioEndpointVolumeCallbackEventArgs> aVolumeChangedHandler)
        {
            //Create device and register default device change notification
            iMultiMediaDeviceEnumerator   = new MMDeviceEnumerator();
            iMultiMediaNotificationClient = new MMNotificationClient(iMultiMediaDeviceEnumerator);
            iMultiMediaNotificationClient.DefaultDeviceChanged += iDefaultDeviceChangedHandler = aDefaultDeviceChangedHandler;
            iMultiMediaDevice = iMultiMediaDeviceEnumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
            //Register to get volume modifications
            iAudioEndpointVolume         = AudioEndpointVolume.FromDevice(iMultiMediaDevice);
            iAudioEndpointVolumeCallback = new AudioEndpointVolumeCallback();
            iAudioEndpointVolumeCallback.NotifyRecived += iVolumeChangedHandler = aVolumeChangedHandler;
            iAudioEndpointVolume.RegisterControlChangeNotify(iAudioEndpointVolumeCallback);

            if (iVisualizerCount > 0)
            {
                // We probably got restarted, make sure visualization is running if needed
                StartAudioVisualization();
            }
        }
        public void Dispose()
        {
            // Client up our MM objects in reverse order
            if (iAudioEndpointVolumeMixerCallback != null && iAudioEndpointVolume != null)
            {
                iAudioEndpointVolume.UnregisterControlChangeNotify(iAudioEndpointVolumeMixerCallback);
            }

            if (iAudioEndpointVolumeMixerCallback != null)
            {
                iAudioEndpointVolumeMixerCallback.NotifyRecived -= iVolumeChangedHandler;
                iAudioEndpointVolumeMixerCallback = null;
            }

            if (iAudioEndpointVolume != null)
            {
                iAudioEndpointVolume.Dispose();
                iAudioEndpointVolume = null;
            }

            if (_mMdevice != null)
            {
                _mMdevice.Dispose();
                _mMdevice = null;
            }

            if (iMultiMediaNotificationClient != null)
            {
                iMultiMediaNotificationClient.DefaultDeviceChanged -= iDefaultDeviceChangedHandler;
                iMultiMediaNotificationClient.Dispose();
                iMultiMediaNotificationClient = null;
            }

            if (_mMdeviceEnumerator != null)
            {
                _mMdeviceEnumerator.Dispose();
                _mMdeviceEnumerator = null;
            }
            Stop();
            Close();
        }
Example #16
0
        private void InitializeSoundOut(IWaveSource soundSource)
        {
            // SoundOut implementation which plays the sound
            this.soundOut = new WasapiOut(this.eventSync, this.audioClientShareMode, this.latency, ThreadPriority.Highest);

            // MMNotificationClient
            this.MMNotificationClient = new MMNotificationClient();
            this.MMNotificationClient.DefaultDeviceChanged += this.MMNotificationClient_DefaultDeviceChanged;

            // Initialize the soundOut
            this.notificationSource = new SingleBlockNotificationStream(soundSource.ToSampleSource());
            this.soundOut.Initialize(this.notificationSource.ToWaveSource(16));

            // Create the FFT provider
            this.fftProvider = new FftProvider(this.soundOut.WaveSource.WaveFormat.Channels, FftSize.Fft2048);

            this.notificationSource.SingleBlockRead += this.InputStream_Sample;
            this.soundOut.Stopped += this.SoundOutStoppedHandler;

            this.soundOut.Volume = this.volume;
        }
Example #17
0
        public static void Main()
        {
            var notificationClient = new MMNotificationClient();

            notificationClient.DeviceAdded           += OnDeviceAdded;
            notificationClient.DeviceRemoved         += OnDeviceRemoved;
            notificationClient.DeviceStateChanged    += OnDeviceStateChanged;
            notificationClient.DefaultDeviceChanged  += OnDefaultDeviceChanged;
            notificationClient.DevicePropertyChanged += OnDevicePropertyChanged;

            Console.WriteLine("-- Sound devices ------------------");
            using (var enumerator = new MMDeviceEnumerator())
            {
                foreach (var mmDevice in enumerator.EnumAudioEndpoints(DataFlow.All, DeviceState.All))
                {
                    Console.WriteLine($"{mmDevice.FriendlyName}");
                }
            }
            Console.WriteLine("-----------------------------------\n");

            Console.WriteLine("-- Device notifications -----------");
            Console.ReadKey();
        }
Example #18
0
        public AlarmSystem(bool isController          = false,
                           int micCaptureBoost        = 100,
                           float delayBeforeAlarm     = 0,
                           float delayBeforeOverlay   = 0,
                           float alarmVolume          = 0,
                           float systemVolume         = 0,
                           float threshold            = 100,
                           bool isSoundAlertEnabled   = false,
                           bool isOverlayAlertEnabled = false)
        {
            //_loggingEnabled = Trace.Listeners.Count > 1;
            try
            {
                Trace.TraceInformation("Alarm system init");
                Trace.Indent();
                state = States.Running;
                this._isControllerMode = isController;

                MMNotificationClient deviceNotification = new MMNotificationClient();
                deviceNotification.DefaultDeviceChanged += DeviceNotification_DefaultDeviceChanged;
                deviceNotification.DeviceAdded          += DeviceNotification_DeviceAdded;
                deviceNotification.DeviceRemoved        += DeviceNotification_DeviceRemoved;

                GetCapture(isController);
                Trace.TraceInformation("Sound Capture OK");

                _soundSource = GetSoundSource();
                _soundSource = _soundSource.Loop();
                GetOutputSound();
                Trace.TraceInformation("Sound Out OK");


                this._isSoundAlertEnabled   = isSoundAlertEnabled;
                this._isOverlayAlertEnabled = isOverlayAlertEnabled;
                this._micCaptureBoost       = micCaptureBoost;
                this._delayBeforeAlarm      = delayBeforeAlarm;
                this._delayBeforeOverlay    = delayBeforeOverlay;
                this.AlarmVolume            = alarmVolume;
                this._alarmThreshold        = threshold;

                _systemSimpleAudioVolume = GetSimpleAudioVolume();
                this.SystemVolume        = systemVolume;

                if (!isController)
                {
                    _bgInputListener.WorkerSupportsCancellation = true;
                    _bgInputListener.DoWork             += bgInputListener_DoWork;
                    _bgInputListener.RunWorkerCompleted += bgInputListener_RunWorkerCompleted;

                    _bgInputListener.RunWorkerAsync();
                }
                Trace.TraceInformation("Background worker running");

                #region Timers

                _timerAlarmDelay          = new System.Timers.Timer();
                _timerAlarmDelay.Elapsed += (s, args) =>
                {
                    if (_timerAlarmDelayArgs.ElapsedTime.Seconds >= _delayBeforeAlarm)
                    {
                        _timerAlarmDelayArgs.alarmActive = true;

                        _timerAlarmDelay.Stop();
                        PlayAlarm(!_isControllerMode);
                    }

                    OnUpdateTimerAlarmDelay(this, _timerAlarmDelayArgs);
                };

                _timerOverlayShow          = new System.Timers.Timer();
                _timerOverlayShow.Elapsed += (s, args) =>
                {
                    if (_timerOverlayDelayArgs.ElapsedTime.Seconds >= _delayBeforeOverlay)
                    {
                        _timerOverlayDelayArgs.alarmActive = true;
                        _timerOverlayShow.Stop();
                        Application.Current.Dispatcher.Invoke((Action) delegate { ShowAlertWindow(!_isControllerMode); });
                    }
                    OnUpdateTimerOverlayDelay(this, _timerOverlayDelayArgs);
                    //if (_timerOverlayShow.Dispatcher.HasShutdownStarted)
                    //    _timerOverlayDelayArgs = null;
                };

                _timerOverlayUpdate          = new System.Timers.Timer();
                _timerOverlayUpdate.Interval = 10;
                _timerOverlayUpdate.Elapsed += (s, args) =>
                {
                    _alertOverlay.Update();
                    if (!_overlayWorking)
                    {
                        _timerOverlayUpdate.Stop();
                        if (_alertOverlay != null)
                        {
                            _alertOverlay.Dispose();
                            _alertOverlay = null;
                        }
                    }
                };

                _timerZeroVolumeDelay           = new System.Timers.Timer(10000);
                _timerZeroVolumeDelay.AutoReset = false;
                _timerZeroVolumeDelay.Elapsed  += (s, args) =>
                {
                    _currentCaptureRole -= 1;
                    if (_currentCaptureRole < 0)
                    {
                        _currentCaptureRole = Role.Communications;
                    }
                    GetCapture(isController);
                };
                _timerZeroVolumeDelay.Start();
                #endregion

                Trace.TraceInformation("Timers initialized");
                Trace.TraceInformation("Alarm System up and running!");
                Trace.Unindent();
            }
            catch (Exception e)
            {
                Trace.TraceError(e.Message);
                Trace.TraceError(e.StackTrace);
                Application.Current.Shutdown();
            }
        }
        //    private ObservableAsPropertyHelper<ObservableCollection<AudioMeterModel>> _audioMeters;

        public MainWindowViewModel()
        {
            _deviceEnumerator   = new MMDeviceEnumerator();
            _notificationClient = new MMNotificationClient(_deviceEnumerator);

            CaptureService.ItemsUpdated.ObserveOn(RxApp.MainThreadScheduler).Subscribe(x =>
            {
                if (AudioMeters.Count == 0)
                {
                    foreach (var audioMeterModel in x)
                    {
                        AudioMeters.Add(audioMeterModel);
                    }

                    return;
                }

                if (PeakVolume > 0)
                {
                    if (x[0].Value > PeakVolume + PeakOffset)
                    {
                        Console.WriteLine("ALERT");
                    }
                }
                test.Add(x[0].Value);
                for (var i = 0; i < x.Count; i++)
                {
                    AudioMeters[i] = x[i];
                }
            });


            UpdateDevices = ReactiveCommand.Create(() =>
            {
                Devices.Clear();
                foreach (var device in _deviceEnumerator.EnumAudioEndpoints(DataFlow.All, DeviceState.Active))
                {
                    Devices.Add(device);
                }
            });

            StartVolumeCapture =
                ReactiveCommand.Create(() => { CaptureService.Start(); }, outputScheduler: RxApp.MainThreadScheduler);
            StopVolumeCapture =
                ReactiveCommand.Create(() => { CaptureService.Stop(); }, outputScheduler: RxApp.MainThreadScheduler);
            PeakVolumeCapture =
                ReactiveCommand.CreateFromObservable <Unit, Unit>(_ =>
            {
                CaptureService.Start();
                test.Clear();
                return(Observable.Return(Unit.Default)
                       .Delay(TimeSpan.FromSeconds(10))
                       .Do(x => CaptureService.Stop()));
            });
            PeakVolumeCapture.Subscribe(x => PeakVolume = test.Max());
            PeakVolumeCapture.ThrownExceptions.Subscribe(Console.WriteLine);
            Observable.FromEventPattern <DeviceNotificationEventArgs>(
                x => _notificationClient.DeviceAdded += x,
                x => _notificationClient.DeviceAdded -= x).Merge(
                Observable.FromEventPattern <DeviceNotificationEventArgs>(
                    y => _notificationClient.DeviceRemoved += y,
                    y => _notificationClient.DeviceRemoved -= y))
            .ObserveOn(RxApp.MainThreadScheduler)
            .Select(x => Unit.Default)
            .InvokeCommand(UpdateDevices);

            Observable.FromEventPattern <DevicePropertyChangedEventArgs>(
                z => _notificationClient.DevicePropertyChanged += z,
                z => _notificationClient.DevicePropertyChanged -= z)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Select(x => Unit.Default)
            .InvokeCommand(UpdateDevices);
        }
Example #20
0
 static DeviceProvider()
 {
     MMDeviceEnumerator   = new MMDeviceEnumerator();
     MmNotificationClient = new MMNotificationClient();
     MMDeviceEnumerator.RegisterEndpointNotificationCallback(MmNotificationClient);
 }
Example #21
0
 public SoundOutManager(CSCoreEngine engine)
 {
     BaseEngine            = engine;
     _mmNotificationClient = new MMNotificationClient();
 }