Пример #1
0
        public static void DumpCollection(MMDeviceCollection collection)
        {
            foreach (var dev in collection)
            {
                Console.WriteLine("Name: {0}", dev.PropertyStore[PropertyStore.FriendlyName]);
                Console.WriteLine("Desc: {0}", dev.PropertyStore[PropertyStore.DeviceDesc]);
                Console.WriteLine("-----------------------------------------------");
                foreach (var item in dev.PropertyStore)
                {
                    try
                    {
                        Console.WriteLine("Key: {0}\nValue: {1}\n\n", item.Key.PropertyID, item.Value.GetValue());
                    }
                    catch (Exception)
                    {
                    }
                }

                dev.Dispose();
            }
        }
Пример #2
0
        /// <summary>
        /// Initialise the waveIn stream.
        /// </summary>
        /// <param name="format">The audio wave format.</param>
        /// <param name="audioRecordingFormat">The audio recording format.</param>
        private void Init(WaveFormatProvider format, AudioRecordingFormat audioRecordingFormat)
        {
            _audioFormat = audioRecordingFormat;

            // Get all the catpure devices.
            MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();
            MMDeviceCollection devices = DevEnum.EnumerateAudioEndPoints(EDataFlow.Capture, EDeviceState.Active);

            // Select the device index.
            _mmDevice = devices[_device.Index];

            // If null the setup defaults.
            if (format == null)
            {
                // Select the provider.
                switch (audioRecordingFormat)
                {
                case AudioRecordingFormat.WasapiLoopback:
                    _waveIn = new WasapiLoopbackCapture(_mmDevice);
                    break;

                case AudioRecordingFormat.Wasapi:
                    _waveIn            = new WasapiCapture(_mmDevice);
                    _waveIn.WaveFormat = new WaveFormatProvider(8000, 16, 1);
                    break;

                case AudioRecordingFormat.WaveInEvent:
                    _waveIn = new WaveInEvent()
                    {
                        DeviceNumber = _device.Index, BufferMilliseconds = _bufferMilliseconds
                    };
                    _waveIn.WaveFormat = new WaveFormatProvider(8000, 16, 1);
                    break;

                case AudioRecordingFormat.WaveIn:
                default:
                    _waveIn = new WaveIn()
                    {
                        DeviceNumber = _device.Index, BufferMilliseconds = _bufferMilliseconds
                    };
                    _waveIn.WaveFormat = new WaveFormatProvider(8000, 16, 1);
                    break;
                }
            }
            else
            {
                // Select the provider.
                switch (audioRecordingFormat)
                {
                case AudioRecordingFormat.WasapiLoopback:
                    _waveIn = new WasapiLoopbackCapture(_mmDevice);
                    break;

                case AudioRecordingFormat.Wasapi:
                    _waveIn            = new WasapiCapture(_mmDevice);
                    _waveIn.WaveFormat = format;
                    break;

                case AudioRecordingFormat.WaveInEvent:
                    _waveIn = new WaveInEvent()
                    {
                        DeviceNumber = _device.Index, BufferMilliseconds = _bufferMilliseconds
                    };
                    _waveIn.WaveFormat = format;
                    break;

                case AudioRecordingFormat.WaveIn:
                default:
                    _waveIn = new WaveIn()
                    {
                        DeviceNumber = _device.Index, BufferMilliseconds = _bufferMilliseconds
                    };
                    _waveIn.WaveFormat = format;
                    break;
                }
            }

            // Set the capture.
            _waveIn.DataAvailable    += _waveIn_DataAvailable;
            _waveIn.RecordingStopped += _waveIn_RecordingStopped;
        }
Пример #3
0
        void ParseJSONPacket(string json)
        {
            Console.WriteLine("Parsing: " + json);

            dynamic data = DynamicJson.Parse(json);

            string command = "";

            try
            {
                command = data.c;
            }
            catch
            {
                Console.WriteLine("Command identifier not found...");
            }

            switch (command)
            {
            case Constants.Commands.DISCONNECT:
                DisconnectClient();
                break;

            case Constants.Commands.UPDATE_OBJECT:

                break;

            case Constants.Commands.UPDATE_PAGE:
                Client.CurrentPage = data.d;
                Notif("Changed client's current page to: " + Client.CurrentPage);
                break;

            case Constants.Commands.PING:
                SendMessage("{\"" + Constants.Commands.PONG + "\": \"\"}", true);
                break;

            case Constants.Commands.PONG:
                if (stopwatch.IsRunning)
                {
                    stopwatch.Stop();
                    Console.WriteLine("Ping to client: " + stopwatch.ElapsedMilliseconds + "ms");
                }
                else
                {
                    Error(Constants.ErrorType.InvalidlyTimedCommand, "Unable to output client response time due to the timer not running.");
                }
                break;

            case Constants.Commands.REQUEST_OUTPUT_DEVICES:
                MMDeviceCollection coll    = DevEnum.EnumerateAudioEndPoints(EDataFlow.eRender, EDeviceState.DEVICE_STATE_ACTIVE);
                MMDevice           defoutd = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);

                string output = "{\"" + Constants.Commands.REQUEST_OUTPUT_DEVICES + "\":[";

                for (int i = 0; i < coll.Count; i++)
                {
                    output += "[\"" + coll[i].ID + "\",\"" + coll[i].FriendlyName + "\", " + (coll[i].ID == defoutd.ID).ToString().ToLower() + "],";
                }

                output = output.Remove(output.Length - 1, 1);

                output += "]}";
                SendMessage(output, true);
                break;

            case Constants.Commands.REQUEST_INPUT_DEVICES:
                foreach (KeyValuePair <int, string> pair in InputDevices)
                {
                    DevEnum.GetDevice(pair.Value).AudioEndpointVolume.OnVolumeNotification -= InputDeviceVolChange;
                }
                InputDevices.Clear();
                MMDeviceCollection coll2 = DevEnum.EnumerateAudioEndPoints(EDataFlow.eCapture, EDeviceState.DEVICE_STATE_ACTIVE);

                string output2 = "{\"" + Constants.Commands.REQUEST_INPUT_DEVICES + "\":[";

                for (int i = 0; i < coll2.Count; i++)
                {
                    InputDevices.Add(i, coll2[i].ID);
                    coll2[i].AudioEndpointVolume.OnVolumeNotification += InputDeviceVolChange;
                    output2 += "[\"" + i.ToString() + "\",\"" + coll2[i].FriendlyName + "\", " + coll2[i].AudioEndpointVolume.MasterVolumeLevelScalar * 100 + "],";
                }

                output2 = output2.Remove(output2.Length - 1, 1);

                output2 += "]}";

                SendMessage(output2, true);
                break;

            case Constants.Commands.REQUEST_AUDIO_SESSIONS:

                foreach (AudioSessionListener asl in listeners)
                {
                    asl.ASC.UnregisterAudioSessionNotification(asl);
                    asl.Dispose();
                }

                listeners.Clear();
                SessionCollection scol    = null;
                string            output3 = "";

                try
                {
                    lastDevice   = DevEnum.GetDevice(data.d);
                    lastDeviceID = lastDevice.ID;
                    lastDevice.AudioEndpointVolume.OnVolumeNotification += AudioEndpointVolume_OnVolumeNotification;
                    scol = lastDevice.AudioSessionManager.Sessions;


                    output3 = "{\"" + Constants.Commands.REQUEST_AUDIO_SESSIONS + "\":{\"" + lastDevice.ID + "\": {";

                    output3 += "\"master\": " + lastDevice.AudioEndpointVolume.MasterVolumeLevelScalar * 100 + ",";
                }
                catch { }

                for (int i = 0; i < scol.Count; i++)
                {
                    if (!deadSessionProcessIDs.Contains((int)scol[i].ProcessID))
                    {
                        string name = "";
                        try
                        {
                            name = FileVersionInfo.GetVersionInfo(Process.GetProcessById((int)scol[i].ProcessID).MainModule.FileName).FileDescription.Trim();

                            if (name.Length > 20)
                            {
                                name = Process.GetProcessById((int)scol[i].ProcessID).ProcessName;
                                name = name.First().ToString().ToUpper() + String.Join("", name.Skip(1));
                            }
                        }
                        catch
                        {
                            try
                            {
                                name = Process.GetProcessById((int)scol[i].ProcessID).ProcessName;
                                name = name.First().ToString().ToUpper() + String.Join("", name.Skip(1));
                            }
                            catch
                            {
                                name = scol[i].DisplayName;
                            }
                        }

                        if (name == "Idle")
                        {
                            name = "System Sounds";
                        }

                        AudioSessionListener t = new AudioSessionListener((int)scol[i].ProcessID, scol[i], name);

                        scol[i].RegisterAudioSessionNotification(t);

                        listeners.Add(t);

                        output3 += "\"" + scol[i].ProcessID + "\": [\"" + name + "\", " + scol[i].SimpleAudioVolume.MasterVolume * 100 + "],";
                    }
                }

                output3 = output3.Remove(output3.Length - 1, 1);

                output3 += "} } }";

                SendMessage(output3, true);

                break;

            case Constants.Commands.CHANGE_SESSION_LEVEL:
                if (data.d.pid == "master")
                {
                    try
                    {
                        lastDevice = DevEnum.GetDevice(lastDeviceID);
                        lastDevice.AudioEndpointVolume.MasterVolumeLevelScalar = (float)(data.d.vol / 100);

                        if (lastDevice.AudioEndpointVolume.MasterVolumeLevelScalar == 0)
                        {
                            lastDevice.AudioEndpointVolume.Mute = true;
                        }
                        else
                        {
                            lastDevice.AudioEndpointVolume.Mute = false;
                        }

                        lastChangeSessionLevelTime = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds;
                        lastChangedVol             = new ProcessVolumeInt(-69001, (int)data.d.vol, ((int)data.d.vol == 0));
                    }
                    catch { }
                }
                else
                {
                    List <AudioSessionListener> asls = listeners.Where(value => value.ProcessID.ToString() == data.d.pid).ToList();
                    foreach (AudioSessionListener asl in asls)
                    {
                        asl.ASC.SimpleAudioVolume.MasterVolume = (float)(data.d.vol / 100);

                        if ((int)data.d.vol == 0)
                        {
                            asl.ASC.SimpleAudioVolume.Mute = true;
                        }
                        else
                        {
                            asl.ASC.SimpleAudioVolume.Mute = false;
                        }

                        lastChangedVol = new ProcessVolumeInt(asl.ProcessID, (int)data.d.vol, ((int)data.d.vol == 0));
                    }

                    lastChangeSessionLevelTime = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds;

                    /*foreach (AudioSessionListener asl2 in listeners)
                     * {
                     *  if (asl2.ProcessID.ToString() == data.d.pid)
                     *  {
                     *      asl2.ASC.SimpleAudioVolume.MasterVolume = (float)(data.d.vol / 100);
                     *      break;
                     *  }
                     * }*/
                }
                break;

            case Constants.Commands.CHANGE_INPUT_LEVEL:
                MMDevice dev = DevEnum.GetDevice(InputDevices[Convert.ToInt32(data.d[0])]);
                dev.AudioEndpointVolume.MasterVolumeLevelScalar = (float)(data.d[1] / 100);
                lastChangedVolD            = new DeviceVolumeInt(InputDevices[Convert.ToInt32(data.d[0])], Convert.ToInt32(data.d[1]), (bool)(Convert.ToInt32(data.d[1]) == 0));
                lastChangeSessionLevelTime = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds;
                break;

            case Constants.Commands.REQUEST_TIME_ZONE:
                SendMessage("{\"" + Constants.Commands.REQUEST_TIME_ZONE + "\": \"" + olsonmap.Find(System.TimeZoneInfo.Local.Id) + "\"}", true);
                break;
            }
        }
Пример #4
0
        // Cmdlet execution
        protected override void ProcessRecord()
        {
            // Create a new MMDeviceEnumerator
            MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();
            // Create a MMDeviceCollection of every devices that are enabled
            MMDeviceCollection DeviceCollection = DevEnum.EnumerateAudioEndPoints(EDataFlow.eAll, EDeviceState.DEVICE_STATE_ACTIVE);

            // If the InputObject parameter received a value
            if (inputObject != null)
            {
                // For every MMDevice in DeviceCollection
                for (int i = 0; i < DeviceCollection.Count; i++)
                {
                    // If this MMDevice's ID is the same as the ID of the MMDevice received by the InputObject parameter
                    if (DeviceCollection[i].ID == inputObject.ID)
                    {
                        // Create a new audio PolicyConfigClient
                        PolicyConfigClient client = new PolicyConfigClient();
                        // Using PolicyConfigClient, set the given device as the default playback communication device
                        client.SetDefaultEndpoint(DeviceCollection[i].ID, ERole.eCommunications);
                        // Using PolicyConfigClient, set the given device as the default playback device
                        client.SetDefaultEndpoint(DeviceCollection[i].ID, ERole.eMultimedia);

                        // Output the result of the creation of a new AudioDevice while assining it the an index, and the MMDevice itself, and a default value of true
                        WriteObject(new AudioDevice(i + 1, DeviceCollection[i], true));

                        // Stop checking for other parameters
                        return;
                    }
                }

                // Throw an exception about the received device not being found
                throw new System.ArgumentException("No such enabled AudioDevice found");
            }

            // If the ID parameter received a value
            if (!string.IsNullOrEmpty(id))
            {
                // For every MMDevice in DeviceCollection
                for (int i = 0; i < DeviceCollection.Count; i++)
                {
                    // If this MMDevice's ID is the same as the string received by the ID parameter
                    if (string.Compare(DeviceCollection[i].ID, id, System.StringComparison.CurrentCultureIgnoreCase) == 0)
                    {
                        // Create a new audio PolicyConfigClient
                        PolicyConfigClient client = new PolicyConfigClient();
                        // Using PolicyConfigClient, set the given device as the default communication device (for its type)
                        client.SetDefaultEndpoint(DeviceCollection[i].ID, ERole.eCommunications);
                        // Using PolicyConfigClient, set the given device as the default device (for its type)
                        client.SetDefaultEndpoint(DeviceCollection[i].ID, ERole.eMultimedia);

                        // Output the result of the creation of a new AudioDevice while assining it the index, and the MMDevice itself, and a default value of true
                        WriteObject(new AudioDevice(i + 1, DeviceCollection[i], true));

                        // Stop checking for other parameters
                        return;
                    }
                }

                // Throw an exception about the received ID not being found
                throw new System.ArgumentException("No enabled AudioDevice found with that ID");
            }

            // If the Index parameter received a value
            if (index != null)
            {
                // If the Index is valid
                if (index.Value >= 1 && index.Value <= DeviceCollection.Count)
                {
                    // Create a new audio PolicyConfigClient
                    PolicyConfigClient client = new PolicyConfigClient();
                    // Using PolicyConfigClient, set the given device as the default communication device (for its type)
                    client.SetDefaultEndpoint(DeviceCollection[index.Value - 1].ID, ERole.eCommunications);
                    // Using PolicyConfigClient, set the given device as the default device (for its type)
                    client.SetDefaultEndpoint(DeviceCollection[index.Value - 1].ID, ERole.eMultimedia);

                    // Output the result of the creation of a new AudioDevice while assining it the index, and the MMDevice itself, and a default value of true
                    WriteObject(new AudioDevice(index.Value, DeviceCollection[index.Value - 1], true));

                    // Stop checking for other parameters
                    return;
                }
                else
                {
                    // Throw an exception about the received Index not being found
                    throw new System.ArgumentException("No enabled AudioDevice found with that Index");
                }
            }

            // If the PlaybackMute parameter received a value
            if (playbackmute != null)
            {
                // Set the mute state of the default playback device to that of the boolean value received by the Cmdlet
                DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia).AudioEndpointVolume.Mute = (bool)playbackmute;
            }

            // If the PlaybackMuteToggle paramter was called
            if (playbackmutetoggle)
            {
                // Toggle the mute state of the default playback device
                DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia).AudioEndpointVolume.Mute = !DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia).AudioEndpointVolume.Mute;
            }

            // If the PlaybackVolume parameter received a value
            if (playbackvolume != null)
            {
                // Set the volume level of the default playback device to that of the float value received by the PlaybackVolume parameter
                DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia).AudioEndpointVolume.MasterVolumeLevelScalar = (float)playbackvolume / 100.0f;
            }

            // If the RecordingMute parameter received a value
            if (recordingmute != null)
            {
                // Set the mute state of the default recording device to that of the boolean value received by the Cmdlet
                DevEnum.GetDefaultAudioEndpoint(EDataFlow.eCapture, ERole.eMultimedia).AudioEndpointVolume.Mute = (bool)recordingmute;
            }

            // If the RecordingMuteToggle paramter was called
            if (recordingmutetoggle)
            {
                // Toggle the mute state of the default recording device
                DevEnum.GetDefaultAudioEndpoint(EDataFlow.eCapture, ERole.eMultimedia).AudioEndpointVolume.Mute = !DevEnum.GetDefaultAudioEndpoint(EDataFlow.eCapture, ERole.eMultimedia).AudioEndpointVolume.Mute;
            }

            // If the RecordingVolume parameter received a value
            if (recordingvolume != null)
            {
                // Set the volume level of the default recording device to that of the float value received by the RecordingVolume parameter
                DevEnum.GetDefaultAudioEndpoint(EDataFlow.eCapture, ERole.eMultimedia).AudioEndpointVolume.MasterVolumeLevelScalar = (float)recordingvolume / 100.0f;
            }
        }
Пример #5
0
        // Cmdlet execution
        protected override void ProcessRecord()
        {
            // Create a new MMDeviceEnumerator
            MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();
            // Create a MMDeviceCollection of every devices that are enabled
            MMDeviceCollection DeviceCollection = DevEnum.EnumerateAudioEndPoints(EDataFlow.eAll, EDeviceState.DEVICE_STATE_ACTIVE);

            // If the List switch parameter was called
            if (list)
            {
                // For every MMDevice in DeviceCollection
                for (int i = 0; i < DeviceCollection.Count; i++)
                {
                    // If this MMDevice's ID is either, the same the default playback device's ID, or the same as the default recording device's ID
                    if (DeviceCollection[i].ID == DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia).ID || DeviceCollection[i].ID == DevEnum.GetDefaultAudioEndpoint(EDataFlow.eCapture, ERole.eMultimedia).ID)
                    {
                        // Output the result of the creation of a new AudioDevice while assining it an index, and the MMDevice itself, and a default value of true
                        WriteObject(new AudioDevice(i + 1, DeviceCollection[i], true));
                    }
                    else
                    {
                        // Output the result of the creation of a new AudioDevice while assining it an index, and the MMDevice itself
                        WriteObject(new AudioDevice(i + 1, DeviceCollection[i]));
                    }
                }

                // Stop checking for other parameters
                return;
            }

            // If the ID parameter received a value
            if (!string.IsNullOrEmpty(id))
            {
                // For every MMDevice in DeviceCollection
                for (int i = 0; i < DeviceCollection.Count; i++)
                {
                    // If this MMDevice's ID is the same as the string received by the ID parameter
                    if (string.Compare(DeviceCollection[i].ID, id, System.StringComparison.CurrentCultureIgnoreCase) == 0)
                    {
                        // If this MMDevice's ID is either, the same the default playback device's ID, or the same as the default recording device's ID
                        if (DeviceCollection[i].ID == DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia).ID || DeviceCollection[i].ID == DevEnum.GetDefaultAudioEndpoint(EDataFlow.eCapture, ERole.eMultimedia).ID)
                        {
                            // Output the result of the creation of a new AudioDevice while assining it an index, and the MMDevice itself, and a default value of true
                            WriteObject(new AudioDevice(i + 1, DeviceCollection[i], true));
                        }
                        else
                        {
                            // Output the result of the creation of a new AudioDevice while assining it an index, and the MMDevice itself
                            WriteObject(new AudioDevice(i + 1, DeviceCollection[i]));
                        }

                        // Stop checking for other parameters
                        return;
                    }
                }

                // Throw an exception about the received ID not being found
                throw new System.ArgumentException("No AudioDevice with that ID");
            }

            // If the Index parameter received a value
            if (index != null)
            {
                // If the Index is valid
                if (index.Value >= 1 && index.Value <= DeviceCollection.Count)
                {
                    // If the ID of the MMDevice associated with the Index is the same as, either the ID of the default playback device, or the ID of the default recording device
                    if (DeviceCollection[index.Value - 1].ID == DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia).ID || DeviceCollection[index.Value - 1].ID == DevEnum.GetDefaultAudioEndpoint(EDataFlow.eCapture, ERole.eMultimedia).ID)
                    {
                        // Output the result of the creation of a new AudioDevice while assining it the an index, and the MMDevice itself, and a default value of true
                        WriteObject(new AudioDevice(index.Value, DeviceCollection[index.Value - 1], true));

                        // Stop checking for other parameters
                        return;
                    }
                    else
                    {
                        // Output the result of the creation of a new AudioDevice while assining it the an index, and the MMDevice itself, and a default value of false
                        WriteObject(new AudioDevice(index.Value, DeviceCollection[index.Value - 1], false));

                        // Stop checking for other parameters
                        return;
                    }
                }
                else
                {
                    // Throw an exception about the received Index not being found
                    throw new System.ArgumentException("No AudioDevice with that Index");
                }
            }

            // If the Playback switch parameter was called
            if (playback)
            {
                // For every MMDevice in DeviceCollection
                for (int i = 0; i < DeviceCollection.Count; i++)
                {
                    // If this MMDevice's ID is the same the default playback device's ID
                    if (DeviceCollection[i].ID == DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia).ID)
                    {
                        // Output the result of the creation of a new AudioDevice while assining it an index, and the MMDevice itself, and a default value of true
                        WriteObject(new AudioDevice(i + 1, DeviceCollection[i], true));
                    }
                }

                // Stop checking for other parameters
                return;
            }

            // If the PlaybackMute switch parameter was called
            if (playbackmute)
            {
                // Output the mute state of the default playback device
                WriteObject(DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia).AudioEndpointVolume.Mute);

                // Stop checking for other parameters
                return;
            }

            // If the PlaybackVolume switch parameter was called
            if (playbackvolume)
            {
                // Output the current volume level of the default playback device
                WriteObject(string.Format("{0}%", DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia).AudioEndpointVolume.MasterVolumeLevelScalar * 100));

                // Stop checking for other parameters
                return;
            }

            // If the Recording switch parameter was called
            if (recording)
            {
                // For every MMDevice in DeviceCollection
                for (int i = 0; i < DeviceCollection.Count; i++)
                {
                    // If this MMDevice's ID is the same the default recording device's ID
                    if (DeviceCollection[i].ID == DevEnum.GetDefaultAudioEndpoint(EDataFlow.eCapture, ERole.eMultimedia).ID)
                    {
                        // Output the result of the creation of a new AudioDevice while assining it an index, and the MMDevice itself, and a default value of true
                        WriteObject(new AudioDevice(i + 1, DeviceCollection[i], true));
                    }
                }

                // Stop checking for other parameters
                return;
            }

            // If the RecordingMute switch parameter was called
            if (recordingmute)
            {
                // Output the mute state of the default recording device
                WriteObject(DevEnum.GetDefaultAudioEndpoint(EDataFlow.eCapture, ERole.eMultimedia).AudioEndpointVolume.Mute);

                // Stop checking for other parameters
                return;
            }

            // If the RecordingVolume switch parameter was called
            if (recordingvolume)
            {
                // Output the current volume level of the default recording device
                WriteObject(string.Format("{0}%", DevEnum.GetDefaultAudioEndpoint(EDataFlow.eCapture, ERole.eMultimedia).AudioEndpointVolume.MasterVolumeLevelScalar * 100));

                // Stop checking for other parameters
                return;
            }
        }
Пример #6
0
        static void Main(string [] args)
        {
            AttachConsole(ATTACH_PARENT_PROCESS);
            Debug.WriteLine(" ");
            Console.WriteLine(" ");

            var options = new Options();

            options.szFormat = "{0}";
            var parser = new CommandLine.Parser(with => with.HelpWriter = Console.Error);

            if (!parser.ParseArgumentsStrict(args, options, () => Environment.Exit(-2)))
            {
                return;
            }

            if (options.iTunes)
            {
                iTunes_Start(options);
                return;
            }

            MMDeviceEnumerator deviceEnum    = new MMDeviceEnumerator();
            MMDevice           defaultDevice = deviceEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, options.deviceRole);

            if (options.bSwitch)
            {
                iTunes_Mute(options);
                bool     b      = defaultDevice.ID.Contains(options.cyrilleDevices [0]);
                MMDevice device = deviceEnum.GetDevice("{0.0.0.00000000}." + options.cyrilleDevices [Convert.ToInt16(b)]);
                SetDefaultEndpoint(options, device);
                return;
            }

            if (options.defaultDevice)
            {
                printDevice(options, defaultDevice);
                FreeConsole();
                return;
            }
            else if (options.allDevices && options.Items.Count == 0)
            {
                options.deviceState = EDeviceState.DEVICE_STATEMASK_ALL;
            }
            if (options.comm)
            {
                options.deviceRole = ERole.eCommunications;
            }

            if (options.Items.Count == 1)
            {
                MMDevice device = deviceEnum.GetDevice("{0.0.0.00000000}." + options.Items [0]);
                SetDefaultEndpoint(options, device);
            }
            else
            {
                MMDeviceCollection audioEndPointsEnum = deviceEnum.EnumerateAudioEndPoints(EDataFlow.eRender, options.deviceState);
                int count = audioEndPointsEnum.Count;
                for (int i = 0; i < count; i++)
                {
                    MMDevice device = audioEndPointsEnum [i];
                    printDevice(options, device);
                    if (options.verbose)
                    {
                        device.DebugProperties();
                    }
                }
            }
            if (options.iTunesMute)
            {
                iTunes_Mute(options);
            }

            FreeConsole();
        }
        public void AddRecordingDevices(MMDeviceCollection devices, MMDevice defaultdevice)
        {
            if (devices == null || cmbRecordingDevice == null)
            {
                return;
            }

            if (InvokeRequired)
            {
                Invoke(new Action <MMDeviceCollection, MMDevice>(AddRecordingDevices), new object[] { devices, defaultdevice });
                return;
            }
            if (IsDisposed)
            {
                return;
            }

            foreach (var device in devices)
            {
                var exists = false;
                for (int i = 0; i < cmbRecordingDevice.Items.Count; i++)
                {
                    if (((MMDevice)cmbRecordingDevice.Items[i]).DeviceID == device.DeviceID)
                    {
                        exists = true;
                    }
                }
                if (!exists)
                {
                    var index = cmbRecordingDevice.Items.Add(device);
                }
            }

            // Select the right device.
            if (!isRecordingDeviceSelected)
            {
                for (int i = 0; i < cmbRecordingDevice.Items.Count; i++)
                {
                    var device = (MMDevice)cmbRecordingDevice.Items[i];
                    if (previousRecordingDeviceID == null && device.DeviceID == defaultdevice.DeviceID)
                    {
                        // Nothing previously selected, select the default device.
                        if (cmbRecordingDevice.SelectedIndex != i)
                        {
                            cmbRecordingDevice.SelectedIndex = i;
                            PlaySilence();
                            isRecordingDeviceSelected = true;
                        }
                    }
                    else if (!string.IsNullOrEmpty(previousRecordingDeviceID) && device.DeviceID == previousRecordingDeviceID)
                    {
                        // Select the previously selected device (only once).
                        cmbRecordingDevice.SelectedIndex = i;
                        PlaySilence();
                        previousRecordingDeviceID = string.Empty;
                        isRecordingDeviceSelected = true;
                    }
                }
            }

            if (!eventHandlerAdded)
            {
                cmbRecordingDevice.SelectedIndexChanged += CmbRecordingDevice_SelectedIndexChanged;
                eventHandlerAdded = true;
            }
        }
Пример #8
0
        //***********************************************************************************************************************************************************************************************************

        #region Control recorder (start, stop, pause, resume)

        /// <summary>
        /// Start a new record
        /// </summary>
        public void StartRecord()
        {
            try
            {
                if (RecordState == RecordStates.RECORDING)
                {
                    return;
                }

                if (TrackInfo == null)
                {
                    _logHandle.Report(new LogEventWarning("Record not started, because no track info exists."));
                    return;
                }
                CreateFilePath();
                if (RecorderRecSettings.FileExistMode == RecorderFileExistModes.SKIP && (System.IO.File.Exists(FileStrWAV) || System.IO.File.Exists(FileStrMP3)))
                {
                    _logHandle.Report(new LogEventWarning("Record (\"" + TrackInfo?.TrackName + "\") not started, because FileExistMode == SKIP and file already exists."));
                    return;
                }

                if (!Directory.Exists(RecorderRecSettings.BasePath))
                {
                    _logHandle.Report(new LogEventWarning("Record (\"" + TrackInfo?.TrackName + "\") not started, because RecordPath is invalid."));
                    return;
                }

                if (WasapiOut.IsSupportedOnCurrentPlatform)
                {
                    _silenceOut = new WasapiOut();
                }
                else
                {
                    _silenceOut = new DirectSoundOut();
                }
                _silenceOut.Initialize(new SilenceGenerator());
                _silenceOut.Play();         //Play silence because otherwise silent parts aren't recorded

                _capture = new WasapiLoopbackCapture();

                MMDeviceEnumerator devEnumerator = new MMDeviceEnumerator();
                MMDeviceCollection mMDevices     = devEnumerator.EnumAudioEndpoints(DataFlow.All, DeviceState.All);

                MMDevice dev;
                if (RecorderRecSettings.RecorderDeviceName.ToLower().Contains("default"))
                {
                    dev = devEnumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
                }
                else
                {
                    dev = mMDevices.Where(d => d.DeviceState == DeviceState.Active && d.FriendlyName == RecorderRecSettings.RecorderDeviceName)?.First();
                }

                if (dev == null)
                {
                    _logHandle.Report(new LogEventError("Record (\"" + TrackInfo?.TrackName + "\") not started, because device \"" + RecorderRecSettings.RecorderDeviceName + "\" wasn't found." + (RecorderRecSettings.RecorderDeviceName.Contains("CABLE Input") ? " Make sure that \"VB Cable\" is installed correctly." : "")));
                    return;
                }

                _capture.Device = dev;
                _capture.Initialize();      // Important!!! First set the capture device, then call Initialize(); otherwise audio is captured from the previous device

                SoundInSource soundInSource    = new SoundInSource(_capture);
                SampleToPcm16 soundInSourcePCM = new SampleToPcm16(soundInSource.ToSampleSource());     //Used to convert _capture to Pcm16 format

                Directory.CreateDirectory(Path.GetDirectoryName(FileStrWAV));
                _wavWriterFormat        = new WaveFormat(_capture.WaveFormat.SampleRate, soundInSourcePCM.WaveFormat.BitsPerSample, _capture.WaveFormat.Channels, AudioEncoding.Pcm, _capture.WaveFormat.ExtraSize); //WAV file must be 16-bit PCM file for normalizing with normalize.exe
                _wavWriter              = new WaveWriter(FileStrWAV, _wavWriterFormat);
                _wavWriterPositionBytes = 0;

                soundInSource.DataAvailable += (s, capData) =>
                {
                    if (RecordState == RecordStates.RECORDING)              //Only record when RecordState is RECORDING
                    {
                        byte[] buffer = new byte[soundInSourcePCM.WaveFormat.BytesPerSecond / 2];
                        int    read;

                        while ((read = soundInSourcePCM.Read(buffer, 0, buffer.Length)) > 0) //keep reading as long as we still get some data
                        {
                            _wavWriter.Write(buffer, 0, read);                               //write the read data to a file
                            _wavWriterPositionBytes += read;
                        }
                    }
                };

                _capture.Start();

                RecordState = RecordStates.RECORDING;
                _logHandle.Report(new LogEventInfo("Record (\"" + TrackInfo?.TrackName + "\") started."));
                WasRecordPaused = false;
            }
            catch (Exception ex)
            {
                _logHandle.Report(new LogEventError("Error while starting record: " + ex.Message));
            }
        }
Пример #9
0
        public SettingsV3()
        {
            InitializeComponent();

            try
            {
                try
                {
                    comboBox1.Text = comboBox1.Items[Convert.ToInt32(Core.Settings.IniReadValue("ACTIONS", "text"))].ToString();
                    comboBox2.Text = comboBox2.Items[Convert.ToInt32(Core.Settings.IniReadValue("ACTIONS", "screen"))].ToString();
                    comboBox3.Text = comboBox3.Items[Convert.ToInt32(Core.Settings.IniReadValue("ACTIONS", "sound"))].ToString();
                }
                catch (Exception z)
                {
                    Out.WriteError("Could not recieve index id from settings file " + z.ToString());
                }

                devices = SoundCapture.GetDevices();

                Keys textkeys = (Keys)Convert.ToInt32(Core.Settings.IniReadValue("HotKeys", "text"));
                hotkeyControl1.HotkeyModifiers = (Keys)getModifier(textkeys);
                hotkeyControl1.Hotkey = removeModifiers(textkeys);

                Keys screenkeys = (Keys)Convert.ToInt32(Core.Settings.IniReadValue("HotKeys", "screen"));
                hotkeyControl2.HotkeyModifiers  =(Keys)getModifier(screenkeys);
                hotkeyControl2.Hotkey = removeModifiers(screenkeys);

                Keys soundkeys = (Keys)Convert.ToInt32(Core.Settings.IniReadValue("HotKeys", "sound"));
                hotkeyControl3.HotkeyModifiers = (Keys)getModifier(soundkeys);
                hotkeyControl3.Hotkey = removeModifiers(soundkeys);

                NextTip(null, null);

                SoundCapture.Init();
                currdev = SoundCapture.RecordDevice;

                Out.WriteDebug("--- SELECTED DEVICE ---");
                Out.WriteDebug(SoundCapture.RecordDevice.FriendlyName + " " + SoundCapture.RecordDevice.ID);
                Out.WriteDebug("-- AVAILABLE DEVICES --");
                foreach (MMDevice device in devices)
                {
                    Out.WriteDebug(device.FriendlyName + " " + device.ID);
                    soundDevices.Items.Add(device.DeviceFriendlyName + " ("+device.FriendlyName+")");
                }
                soundDevices.Text = SoundCapture.DeviceName;

                //WasapiLoopbackCapture wasapi = new WasapiLoopbackCapture(SoundCapture.RecordDevice);

                checkBox2.Checked = Convert.ToBoolean(Convert.ToInt32(Core.Settings.IniReadValue("ScreenCapture", "freeze")));
                comboBox4.Text = comboBox4.Items[Convert.ToInt32(Core.Settings.IniReadValue("TextCapture", "exposure"))].ToString();

                checkBox5.Checked = Convert.ToBoolean(Convert.ToInt32(Core.Settings.IniReadValue("MISC", "ShowSplash")));
                checkBox7.Checked = Convert.ToBoolean(Convert.ToInt32(Core.Settings.IniReadValue("Update", "Disable")));

                RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                string val = ((string)key.GetValue("EasyCapture"));
                checkBox6.Checked = val != string.Empty && val != null;

                CheckAuth();
                CheckAuth2();
                CheckAuth3();

                stuff("general_settings", false);

                bool imgur = Convert.ToBoolean(Convert.ToInt32(Core.Settings.IniReadValue("ScreenCapture", "imgur")));
                bool pastebin = Convert.ToBoolean(Convert.ToInt32(Core.Settings.IniReadValue("TextCapture", "pastebin")));

                imageImgur.Checked = imgur;
                textPB.Checked = pastebin;
                imageEZ.Checked = !imgur;
                textEZ.Checked = !pastebin;

                ignore = false;
            }
            catch (Exception z)
            {
                if (TaskDialog.IsPlatformSupported)
                    TaskDialog.Show(z.ToString(), z.Message, "Loading settings failed");
                else MessageBox.Show(z.ToString(), "Loading settings failed");
                Close();
            }
        }
Пример #10
0
 static MMDeviceCollection GetInputDeviceCollection()
 {
     inputDeviceCollection = MMDE.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.Active);
     return(inputDeviceCollection);
 }
Пример #11
0
 static MMDeviceCollection GetOutputDeviceCollection()
 {
     outputDeviceCollection = MMDE.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active);
     return(outputDeviceCollection);
 }
Пример #12
0
        private void frmMain_Load(object sender, EventArgs e)
        {
            MMDeviceEnumerator enumerator = new MMDeviceEnumerator();

            defaultDevice = enumerator.GetDefaultAudioEndpoint(DataFlow.Capture, Role.Multimedia);
            devices       = enumerator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.Active);

            cmbWasapiDevices.Items.AddRange(devices.ToArray());

            if (cmbWasapiDevices.Items.Count > 0)
            {
                cmbWasapiDevices.SelectedIndex = 0;
            }
            else
            {
                MessageBox.Show("Не обнаружено ни одного устройства для записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }
            totalRecodrTime                 = 0;
            sectionRecordTime               = 0;
            lblTime.Text                    = "";
            tsslDirPath.Text                = "";
            tsslDirPath.Visible             = false;
            cmbCutTimeVariant.SelectedIndex = 0;
            cmbTypeFile.SelectedIndex       = 0;
            // Параметры приложения
            if (Properties.Settings.Default.p_device == 0)
            {
                rbnInputDefault.Checked = true;
            }
            else if (Properties.Settings.Default.p_device > 0 && Properties.Settings.Default.p_device <= cmbWasapiDevices.Items.Count)
            {
                rbnInputSelect.Checked         = true;
                cmbWasapiDevices.SelectedIndex = Properties.Settings.Default.p_device - 1;
            }
            switch (Properties.Settings.Default.p_cut_type)
            {
            case "timer":
                rbnCutTimer.Checked = true;
                break;

            case "clock":
                rbnCutClock.Checked = true;
                break;

            default:
                rbnNoCut.Checked = true;
                break;
            }
            if (Properties.Settings.Default.p_cut_timer >= 5)
            {
                nudCutTime.Value = Properties.Settings.Default.p_cut_timer;
            }
            if (Properties.Settings.Default.p_cut_clock >= 0 && Properties.Settings.Default.p_cut_clock < cmbCutTimeVariant.Items.Count)
            {
                cmbCutTimeVariant.SelectedIndex = Properties.Settings.Default.p_cut_clock;
            }
            if (Directory.Exists(Properties.Settings.Default.p_dir))
            {
                pathToFolderForRecodreFiles = Properties.Settings.Default.p_dir;
                btnRecord.Enabled           = true;
                tsslDirPath.Text            = pathToFolderForRecodreFiles;
                tsslDirPath.Visible         = true;
            }
            if (Properties.Settings.Default.p_save == 0)
            {
                rbnSaveFiles.Checked = true;
            }
            if (Properties.Settings.Default.p_save == 1)
            {
                rbnSaveFolderFiles.Checked = true;
            }
            // Аргументы коммандной строки
            String[] arguments = Environment.GetCommandLineArgs();
            bool     autoStart = false;

            for (int i = 1; i < arguments.Length; i++)
            {
                switch (arguments[i])
                {
                case "--device":
                    if (i + 1 < arguments.Length)
                    {
                        i += 1;
                        int num = Int32.Parse(arguments[i]);
                        if (num == 0)
                        {
                            rbnInputDefault.Checked = true;
                        }
                        else
                        {
                            if (num > 0 && num <= cmbWasapiDevices.Items.Count)
                            {
                                rbnInputSelect.Checked         = true;
                                cmbWasapiDevices.SelectedIndex = num - 1;
                            }
                        }
                    }
                    break;

                case "--save-type-file":
                    rbnSaveFiles.Checked = true;
                    break;

                case "--save-type-folder-file":
                    rbnSaveFolderFiles.Checked = true;
                    break;

                case "--cut-type":
                    if (i + 1 < arguments.Length)
                    {
                        i += 1;
                        switch (arguments[i])
                        {
                        case "no":
                            rbnNoCut.Checked = true;
                            break;

                        case "timer":
                            if (i + 1 < arguments.Length)
                            {
                                i += 1;
                                int num = Int32.Parse(arguments[i]);
                                if (num >= 5)
                                {
                                    rbnCutTimer.Checked = true;
                                    nudCutTime.Value    = num;
                                }
                            }
                            break;

                        case "clock":
                            if (i + 1 < arguments.Length)
                            {
                                i += 1;
                                int num = Int32.Parse(arguments[i]);
                                if (num > 0 && num <= cmbCutTimeVariant.Items.Count)
                                {
                                    cmbCutTimeVariant.SelectedIndex = num - 1;
                                    rbnCutClock.Checked             = true;
                                }
                            }
                            break;

                        default:
                            rbnNoCut.Checked = true;
                            break;
                        }
                    }
                    break;

                case "--dir":
                    if (i + 1 < arguments.Length)
                    {
                        i += 1;
                        if (Directory.Exists(arguments[i]))
                        {
                            pathToFolderForRecodreFiles = arguments[i];
                            btnRecord.Enabled           = true;
                            tsslDirPath.Text            = pathToFolderForRecodreFiles;
                            tsslDirPath.Visible         = true;
                        }
                    }
                    break;

                case "--record":
                    autoStart = true;
                    break;

                case "--title":
                    if (i + 1 < arguments.Length)
                    {
                        i        += 1;
                        this.Text = arguments[i];
                    }
                    break;
                }
            }
            if (autoStart && btnRecord.Enabled)
            {
                btnRecord_Click(sender, e);
            }
        }
Пример #13
0
 public AudioDevice()
 {
     mMDeviceEnumerator = new MMDeviceEnumerator();
     MMDeviceCollection = mMDeviceEnumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active);
 }
Пример #14
0
        public AudioDeviceEnd()
        {
            MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();

            _collections = DevEnum.EnumerateAudioEndPoints(EDataFlow.eAll, EDeviceState.DEVICE_STATE_ACTIVE);
        }
Пример #15
0
 private static void UpdateDevices()
 {
     deviceEnum = new MMDeviceEnumerator();
     deviceCol  = deviceEnum.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.Active);
 }
Пример #16
0
 static AudioManager()
 {
      captureDevices = deviceEnumerator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.Active);
      renderDevices = deviceEnumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active);
 }
Пример #17
0
        public Settings()
        {
            Logger.Log("Initializing Settings");
            InitializeComponent();
            linkLabel1.Links.Add(new LinkLabel.Link()
            {
                LinkData = "https://github.com/Mnaukal/virtual-loop-pedal"
            });
            linkLabel2.Links.Add(new LinkLabel.Link()
            {
                LinkData = "https://github.com/naudio/NAudio"
            });

            Properties.Settings settings = Properties.Settings.Default;

            // load saved values
            numericUpDown_sampleRate.Value   = settings.SampleRate;
            numericUpDown_latency.Value      = settings.DesiredLatency;
            numericUpDown_bufferSize.Value   = settings.BufferSize;
            radioButton_waveOutEvent.Checked = (settings.Driver == "WaveEvent");
            radioButton_asio.Checked         = (settings.Driver == "ASIO");
            radioButton_wasapi.Checked       = (settings.Driver == "Wasapi");

            // enumerate WaveOut devices
            Logger.Log("Loading WaveOut devices");
            if (WaveOut.DeviceCount > 0)
            {
                for (var deviceId = -1; deviceId < WaveOut.DeviceCount; deviceId++)
                {
                    var capabilities = WaveOut.GetCapabilities(deviceId);
                    comboBox_outputWave.Items.Add($"Device {deviceId} ({capabilities.ProductName})");
                }
                comboBox_outputWave.SelectedIndex = (Owner as Pedal) != null ? (Owner as Pedal).settings.WaveOutDeviceNumber + 1 : 0;
            }
            Logger.Log("WaveOut devices loaded");

            // enumerate WaveIn devices
            Logger.Log("Loading WaveIn devices");
            if (WaveIn.DeviceCount > 0)
            {
                for (var deviceId = -1; deviceId < WaveIn.DeviceCount; deviceId++)
                {
                    var capabilities = WaveIn.GetCapabilities(deviceId);
                    comboBox_inputWave.Items.Add($"Device {deviceId} ({capabilities.ProductName})");
                }
                comboBox_inputWave.SelectedIndex = (Owner as Pedal) != null ? (Owner as Pedal).settings.WaveInDeviceNumber + 1 : 0;
            }
            Logger.Log("WaveIn devices loaded");

            // enumerate ASIO devices
            Logger.Log("Loading ASIO devices");
            try
            {
                var asioDriverNames = AsioOut.GetDriverNames();
                foreach (string driverName in asioDriverNames)
                {
                    comboBox_asioDriver.Items.Add(driverName);
                }
                comboBox_asioDriver.SelectedIndex = 0;
                Logger.Log("ASIO devices loaded");
            }
            catch
            {
                // ASIO driver not available
                label_noAsio.Visible = true;
                Logger.Log("ASIO driver not available, disabling ASIO");
            }

            // enumerate WASAPI devices
            Logger.Log("Loading WASAPI devices");
            MMDeviceEnumerator           enumerator    = new MMDeviceEnumerator();
            MMDeviceCollection           endPoints     = enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active);
            List <WasapiDeviceComboItem> outComboItems = new List <WasapiDeviceComboItem>();

            foreach (MMDevice endPoint in endPoints)
            {
                outComboItems.Add(new WasapiDeviceComboItem()
                {
                    Description = endPoint.FriendlyName + " (" + endPoint.DeviceFriendlyName + ")",
                    Device      = endPoint
                });
            }
            comboBox_outputWasapi.DisplayMember = "Description";
            comboBox_outputWasapi.ValueMember   = "Device";
            comboBox_outputWasapi.DataSource    = outComboItems;

            endPoints = enumerator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.Active);
            List <WasapiDeviceComboItem> inComboItems = new List <WasapiDeviceComboItem>();

            foreach (MMDevice endPoint in endPoints)
            {
                inComboItems.Add(new WasapiDeviceComboItem()
                {
                    Description = endPoint.FriendlyName + " (" + endPoint.DeviceFriendlyName + ")",
                    Device      = endPoint
                });
            }
            comboBox_inputWasapi.DisplayMember = "Description";
            comboBox_inputWasapi.ValueMember   = "Device";
            comboBox_inputWasapi.DataSource    = inComboItems;
            Logger.Log("WASAPI devices loaded");
            Logger.Log("Settings initialized successfully");
        }
Пример #18
0
        // thread to animate and unmute microphones
        private void UiThread()
        {
            // hang tight
            P.Dispatcher.Invoke(new UpdateTitleCallback(UpdateTitle), ("hang tight"));

            // sleep a bit
            Thread.Sleep(500);

            // find me some microphones
            P.Dispatcher.Invoke(new UpdateTitleCallback(UpdateTitle), ("finding microphones to fix..."));

            // placeholder for device setting set
            bool setDevice = false;

            // first try the new way, otherwise fallback in the catch
            try
            {
                // get the devices connected
                MMDeviceEnumerator devEnum = new MMDeviceEnumerator();
                MMDeviceCollection devices = devEnum.EnumerateAudioEndPoints(EDataFlow.eCapture, EDeviceState.DEVICE_STATEMASK_ALL);

                // show how many devices we found
                P.Dispatcher.Invoke(new UpdateTitleCallback(UpdateTitle), string.Format("found {0} possible devices", devices.Count));

                // holder for progress spinner
                int t = 0;

                // itterate over devices
                for (int i = 0; i < devices.Count; i++)
                {
                    // itterate over progressbar
                    for (int j = t; j <= 100; j++)
                    {
                        t = j;
                        double d = (((double)(i + 1) / devices.Count) * 100);
                        if (d <= j)
                        {
                            break;
                        }

                        Thread.Sleep(35);
                        P.Dispatcher.Invoke(new UpdateProgressCallback(UpdateProgress), j);
                    }

                    // dont spin too fast
                    Thread.Sleep(1000);

                    // extract device data
                    MMDevice deviceAt = devices[i];
                    string   lowName  = deviceAt.FriendlyName.ToLower();

                    // skip not present devices
                    if (deviceAt.State == EDeviceState.DEVICE_STATE_NOTPRESENT)
                    {
                        // not present
                        P.Dispatcher.Invoke(new UpdateTitleCallback(UpdateTitle), string.Format("skipping {0}, device not present", lowName));
                        continue;
                    }

                    // skip not plugged in devices
                    if (deviceAt.State == EDeviceState.DEVICE_STATE_UNPLUGGED)
                    {
                        // not plugged in
                        P.Dispatcher.Invoke(new UpdateTitleCallback(UpdateTitle), string.Format("skipping {0}, device unplugged", lowName));
                        continue;
                    }

                    // try to unmute and set volume on this device
                    try
                    {
                        deviceAt.AudioEndpointVolume.Mute = false;
                        deviceAt.AudioEndpointVolume.MasterVolumeLevelScalar = 1;
                        P.Dispatcher.Invoke(new UpdateTitleCallback(UpdateTitle), string.Format("{0} : unmute, volume (100%)", lowName));

                        // mark as passed this section if name is microphone
                        if (lowName.Contains("microphone"))
                        {
                            setDevice = true;
                        }
                    }
                    catch
                    {
                        // ignored
                    }
                }

                // did we even find any devices?
                if (devices.Count == 0)
                {
                    // failure, can't continue
                    P.Dispatcher.Invoke(new UpdateTitleCallback(UpdateTitle), "no microphones found");

                    // reset progressbar
                    P.Dispatcher.Invoke(new UpdateProgressCallback(UpdateProgress), new object[] { 0 });

                    // hide the microphone icon
                    Mic.Dispatcher.Invoke(new HideMicCallback(HideMic));

                    // show failure X
                    X.Dispatcher.Invoke(new ShowXCallback(ShowX));
                    return;
                }
            }
            catch
            {
                // fallback option
                MixerNativeLibrary.MicInterface.MuteOrUnMuteAllMics(false);

                // i dunno, always set this to true
                setDevice = true;
            }

            // hide the microphone icon
            Mic.Dispatcher.Invoke(new HideMicCallback(HideMic));

            // did we do some good?
            if (!setDevice)
            {
                // failure, can't continue
                P.Dispatcher.Invoke(new UpdateTitleCallback(UpdateTitle), "all valid microphones unplugged or disabled");

                // reset progressbar
                P.Dispatcher.Invoke(new UpdateProgressCallback(UpdateProgress), new object[] { 0 });

                // show failure X
                X.Dispatcher.Invoke(new ShowXCallback(ShowX));
            }
            else
            {
                // finsh out the progress bar
                P.Dispatcher.Invoke(new UpdateProgressCallback(UpdateProgress), 100);

                // show the checkmark
                CheckMark.Dispatcher.Invoke(new ShowCheckCallback(ShowCheck));

                // done
                P.Dispatcher.Invoke(new UpdateTitleCallback(UpdateTitle), "done with microphone(s)");

                // Zzzz
                Thread.Sleep(2000);

                // reset progressbar
                P.Dispatcher.Invoke(new UpdateProgressCallback(UpdateProgress), new object[] { 0 });

                // hide the check mark
                CheckMark.Dispatcher.Invoke(new HideCheckCallback(HideCheck));

                // show the pulsing chrome icon
                CheckMark.Dispatcher.Invoke(new ShowChromeCallback(ShowChrome));

                // figure out how many chrome processes are open and running
                Process[] chromeInstances = Process.GetProcessesByName("chrome");
                int       total           = chromeInstances.Length;

                // case where no chrome windows open
                if (total <= 0)
                {
                    // indicate chrome restart
                    P.Dispatcher.Invoke(new UpdateTitleCallback(UpdateTitle), "opening chrome...");

                    // open chrome
                    Process.Start(@"chrome.exe");
                }
                else
                {
                    // indicate chrome restart
                    P.Dispatcher.Invoke(new UpdateTitleCallback(UpdateTitle), "restarting chrome...");

                    // restart all instances of chrome, wait for them to all close
                    Process.Start(@"chrome.exe", "chrome://restart");

                    // stopwatch for give up plan
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    while (true)
                    {
                        chromeInstances = Process.GetProcessesByName("chrome");

                        // wait til we reach 2 or less chrome instances
                        // also give up after 45 seconds
                        if (chromeInstances.Length <= 2 || sw.Elapsed.TotalSeconds > 45)
                        {
                            // done
                            break;
                        }
                        else
                        {
                            // make sure the "progress" donut doesnt show less progress over time
                            total = Math.Max(total, chromeInstances.Length);

                            // update th eprogress bar
                            P.Dispatcher.Invoke(new UpdateProgressCallback(UpdateProgress), Math.Ceiling(((total - (double)chromeInstances.Length) / total) * 100));
                        }

                        // dont spin the cpu
                        Thread.Sleep(100);
                    }
                }

                // set to 100% for visual clue
                P.Dispatcher.Invoke(new UpdateProgressCallback(UpdateProgress), 100);

                // hide the pulsing chrome icon
                CheckMark.Dispatcher.Invoke(new HideChromeCallback(HideChrome));

                // show the check mark
                CheckMark.Dispatcher.Invoke(new ShowCheckCallback(ShowCheck));

                // set done and good luck messaging
                P.Dispatcher.Invoke(new UpdateTitleCallback(UpdateTitle), "done, good luck on your exam!");

                // let them read it and wait
                Thread.Sleep(5000);

                // kill this app
                Environment.Exit(0);
            }
        }
Пример #19
0
 static AudioManager()
 {
     captureDevices = deviceEnumerator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.Active);
     renderDevices  = deviceEnumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active);
 }
 public DisposableMMDeviceCollection(MMDeviceCollection collection)
 {
     this._collection = collection;
 }
Пример #21
0
        /// <summary>
        /// Return output devices.
        /// </summary>
        /// <returns></returns>
        public MMDeviceCollection GetListOfOutputDevices()
        {
            MMDeviceCollection deviceList = devicesController.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active);

            return(deviceList);
        }
Пример #22
0
 public Audio(bool muteIfZero = true)
 {
     _muteIfZero = muteIfZero;
     NAudio.CoreAudioApi.MMDeviceEnumerator MMDE = new NAudio.CoreAudioApi.MMDeviceEnumerator();
     activeDevices = MMDE.EnumerateAudioEndPoints(NAudio.CoreAudioApi.DataFlow.Render, NAudio.CoreAudioApi.DeviceState.Active);
 }