public void tick(Object source, ElapsedEventArgs e) { // if (comboboxDevices.SelectedItem != null) // { // var device = (MMDevice)comboboxDevices.SelectedItem; NAudio.CoreAudioApi.MMDeviceEnumerator devEnum = new NAudio.CoreAudioApi.MMDeviceEnumerator(); NAudio.CoreAudioApi.MMDevice defaultDevice = devEnum.GetDefaultAudioEndpoint(NAudio.CoreAudioApi.DataFlow.Render, NAudio.CoreAudioApi.Role.Multimedia); loudness = defaultDevice.AudioMeterInformation.MasterPeakValue * 255; transformedData = FFT(transformedData); int bandWidth = transformedData.Length / 18; for (int i = 0; i < 18; i++) { double sum = 0; for (int j = 0; j < bandWidth; j++) { sum += transformedData[j * 18 + i]; } wavesScaling[i] = sum; } //string concatenated = string.Join("#", loudBandData); //try //{ // if (networking.client.Connected) //{ //networking.SendMessage("L" + concatenated + "#"); //} //} //catch { } }
public IDeviceManualTriggerContext ManualTrigger(DeviceManualTriggerContextOption Option = null) { if (Option != null) { DeviceAddedEventHandler threadSafeEventHandler = DeviceAdded; SixtyBeatAudioDevice device = SixtyBeatAudioDevice.Create(Option.Tag as string); if (device != null) { threadSafeEventHandler?.Invoke(this, device); } return(null); } SixtyBeatAudioDeviceManualTriggerContext ResponseData = new SixtyBeatAudioDeviceManualTriggerContext(); ResponseData.Options = new List <DeviceManualTriggerContextOption>(); var enumerator = new NAudio.CoreAudioApi.MMDeviceEnumerator(); //cycle through all audio devices for (int i = 0; i < WaveIn.DeviceCount; i++) { // these happen to enumate the same order NAudio.CoreAudioApi.MMDevice dev = enumerator.EnumerateAudioEndPoints(NAudio.CoreAudioApi.DataFlow.Capture, NAudio.CoreAudioApi.DeviceState.Active)[i]; string DeviceID = dev.Properties[new NAudio.CoreAudioApi.PropertyKey(DevPKey.Native.PnpDevicePropertyAPINative.DEVPKEY_Audio_InstanceId.fmtid, (int)DevPKey.Native.PnpDevicePropertyAPINative.DEVPKEY_Audio_InstanceId.pid)].Value.ToString(); if (!SixtyBeatAudioDevice.DeviceKnown(DeviceID)) { ResponseData.Options.Add(new DeviceManualTriggerContextOption(dev.FriendlyName, DeviceID)); } } enumerator.Dispose(); return(ResponseData); }
/// <exception cref="InitFailure">If audio device can not be found.</exception> public AudioManager() { Context = System.Threading.Thread.CurrentThread; var mm_enum = new NAudio.CoreAudioApi.MMDeviceEnumerator(); mmdev_media = mm_enum?.GetDefaultAudioEndpoint(NAudio.CoreAudioApi.DataFlow.Render, NAudio.CoreAudioApi.Role.Multimedia); if (mmdev_media == null) { throw new InitFailure("Failed to capture default audio output device."); } Serilog.Log.Information("<Audio> Defalt device: {Device}", mmdev_media.DeviceFriendlyName); mmdev_media.AudioSessionManager.OnSessionCreated += OnSessionCreated; /* * var cfg = Taskmaster.Config.Load(configfile); * * foreach (var section in cfg) * { * * } */ }
void Dispose(bool disposing) { if (disposed) { return; } if (disposing) { if (Taskmaster.Trace) { Log.Verbose("Disposing microphone monitor..."); } if (m_dev != null) { m_dev.AudioEndpointVolume.OnVolumeNotification -= VolumeChangedHandler; m_dev = null; } if (micstatsdirty) { var stats = Taskmaster.Config.Load(statfile); stats.Config["Statistics"]["Corrections"].IntValue = Corrections; stats.Save(); } } disposed = true; }
public SixtyBeatAudioDevice(string deviceId) { var enumerator = new NAudio.CoreAudioApi.MMDeviceEnumerator(); //cycle through all audio devices int audioDeviceNumber = -1; for (int i = 0; i < WaveIn.DeviceCount; i++) { // these happen to enumate the same order NAudio.CoreAudioApi.MMDevice dev = enumerator.EnumerateAudioEndPoints(NAudio.CoreAudioApi.DataFlow.Capture, NAudio.CoreAudioApi.DeviceState.Active)[i]; //Guid scratch = (Guid)(dev.Properties[new NAudio.CoreAudioApi.PropertyKey(DevPKey.Native.PnpDevicePropertyAPINative.DEVPKEY_Device_ContainerId.fmtid, (int)DevPKey.Native.PnpDevicePropertyAPINative.DEVPKEY_Device_ContainerId.pid)].Value); //blder.AppendLine($"{i}\t{scratch}\t{dev}"); string ItemDeviceID = dev.Properties[new NAudio.CoreAudioApi.PropertyKey(DevPKey.Native.PnpDevicePropertyAPINative.DEVPKEY_Audio_InstanceId.fmtid, (int)DevPKey.Native.PnpDevicePropertyAPINative.DEVPKEY_Audio_InstanceId.pid)].Value.ToString(); //Dictionary<DevPKey.Native.PnpDevicePropertyAPINative.DEVPROPKEY, string> properties = DevPKey.PnpDevicePropertyAPI.GetDeviceProperties(DeviceID); if (ItemDeviceID == deviceId) { audioDeviceNumber = i; this.DeviceID = ItemDeviceID; break; } } Properties = new Dictionary <string, dynamic>(); previousValues = new RingBuffer <Int16>(BUFFER); previousAbsValues = new RingBuffer <Int16>(BUFFER); wi = new WaveInEvent(); wi.DeviceNumber = audioDeviceNumber; wi.WaveFormat = new NAudio.Wave.WaveFormat(RATE, 1); wi.BufferMilliseconds = (int)((double)BUFFERSIZE / (double)RATE * 1000.0); wi.DataAvailable += new EventHandler <WaveInEventArgs>(AudioDataAvailable); }
/// <summary> /// 系统静音/取消系统静音 /// </summary> public static void SethMute() { NAudio.CoreAudioApi.MMDeviceEnumerator MMDE = new NAudio.CoreAudioApi.MMDeviceEnumerator(); //Get all the devices, no matter what condition or status NAudio.CoreAudioApi.MMDevice dev = MMDE.GetDefaultAudioEndpoint(NAudio.CoreAudioApi.DataFlow.Render, NAudio.CoreAudioApi.Role.Communications); dev.AudioEndpointVolume.Mute = !dev.AudioEndpointVolume.Mute; }
public LSDevice() { id = name = null; isRec = isPlay = false; serializationData = "undef"; capt1 = "undef"; capt2 = "undef"; mm = null; wf = null; }
public AudioDeviceViewModel(NAudio.CoreAudioApi.MMDevice audioDevice) { synchronizationContext = SynchronizationContext.Current; Device = audioDevice; if (Device.State == NAudio.CoreAudioApi.DeviceState.Active && Device.DataFlow == NAudio.CoreAudioApi.DataFlow.Render) { float MaxDecibels = Device.AudioEndpointVolume.VolumeRange.MaxDecibels; float MinDecibels = Device.AudioEndpointVolume.VolumeRange.MinDecibels; Misc.LogStatics.Debug("Device:{0} MasterLevel={1} MasterScalar={2} MaxDecibels={3} MinDecibels={4}", Device.FriendlyName, Device.AudioEndpointVolume.MasterVolumeLevel, Device.AudioEndpointVolume.MasterVolumeLevelScalar, MaxDecibels, MinDecibels); try { int ChannelCount = Math.Max(Device.AudioEndpointVolume.Channels.Count, Device.AudioMeterInformation.PeakValues.Count); _Master.Volume = Math.Round(Device.AudioEndpointVolume.MasterVolumeLevelScalar * 100.0); _Master.Peek = Device.AudioMeterInformation.MasterPeakValue; _Channels = new ChannelViewModel[ChannelCount]; for (int iChannel = 0; iChannel < ChannelCount; ++iChannel) { double ChVol = 0.0; double ChPeek = 0.0; if (iChannel < Device.AudioEndpointVolume.Channels.Count) { NAudio.CoreAudioApi.AudioEndpointVolumeChannel Channel = Device.AudioEndpointVolume.Channels[iChannel]; ChVol = Math.Round(Channel.VolumeLevelScalar * 100.0); Misc.LogStatics.Debug("\tCH:{0} Level={1} Scalar={2}", iChannel, Channel.VolumeLevel, Channel.VolumeLevelScalar); } if (iChannel < Device.AudioEndpointVolume.Channels.Count) { ChPeek = Device.AudioMeterInformation.PeakValues[iChannel]; } _Channels[iChannel] = new ChannelViewModel(ChVol, ChPeek); } } catch (Exception ex) { Misc.LogStatics.Debug("{0}", ex); } try { Device.AudioEndpointVolume.OnVolumeNotification += AudioEndpointVolume_OnVolumeNotification; PeekUpdateTimer.Elapsed += PeekUpdateTimer_Elapsed; PeekUpdateTimer.Start(); } catch (Exception ex) { Misc.LogStatics.Debug("{0}", ex); } } }
public Form1() { InitializeComponent(); NAudio.CoreAudioApi.MMDeviceEnumerator enumerator = new NAudio.CoreAudioApi.MMDeviceEnumerator(); var devices = enumerator.EnumerateAudioEndPoints(NAudio.CoreAudioApi.DataFlow.Render, NAudio.CoreAudioApi.DeviceState.Active); NAudio.CoreAudioApi.MMDeviceEnumerator devEnum = new NAudio.CoreAudioApi.MMDeviceEnumerator(); NAudio.CoreAudioApi.MMDevice defaultDevice = devEnum.GetDefaultAudioEndpoint(NAudio.CoreAudioApi.DataFlow.Render, NAudio.CoreAudioApi.Role.Multimedia); comboBox1.Items.AddRange(devices.ToArray()); CoreAudioDevice defaultPlaybackDevice = new CoreAudioController().DefaultPlaybackDevice; }
private void GetDevice() { listBox1.Items.Add("GetDevice"); try { //Instantiate an Enumerator to find audio devices NAudio.CoreAudioApi.MMDeviceEnumerator MMDE = new NAudio.CoreAudioApi.MMDeviceEnumerator(); //Get all the devices, no matter what condition or status NAudio.CoreAudioApi.MMDeviceCollection DevCol = MMDE.EnumerateAudioEndPoints(NAudio.CoreAudioApi.DataFlow.All, NAudio.CoreAudioApi.DeviceState.All); //Loop through all devices foreach (NAudio.CoreAudioApi.MMDevice dev in DevCol) { try { if (dev.State == NAudio.CoreAudioApi.DeviceState.Active) { listBox1.Items.Add("Device 찾음"); listBox1.Items.Add(dev.FriendlyName); cbDevice.Items.Add(dev); } else { Console.WriteLine("Ignoring device " + dev.FriendlyName + " with state " + dev.State); } } catch (Exception ex) { listBox1.Items.Add(ex.ToString()); } } } catch (Exception ex) { listBox1.Items.Add(ex.ToString()); } if (cbDevice.Items.Count > 0) { cbDevice.SelectedIndex = 0; master = (NAudio.CoreAudioApi.MMDevice)cbDevice.Items[0]; } }
public bool test() { tested = true; wf = null; try { if (mm == null || mm.State == NAudio.CoreAudioApi.DeviceState.NotPresent || mm.State == NAudio.CoreAudioApi.DeviceState.Unplugged) { return(false); } capt1 = mm.FriendlyName; // windows name capt2 = mm.DeviceFriendlyName; // just device if (capt1.EndsWith(capt2 + ")")) { capt1 = capt1.Substring(0, capt1.Length - (capt2.Length + 3)); } isRec = mm.DataFlow == NAudio.CoreAudioApi.DataFlow.All || mm.DataFlow == NAudio.CoreAudioApi.DataFlow.Capture; isPlay = mm.DataFlow == NAudio.CoreAudioApi.DataFlow.All || mm.DataFlow == NAudio.CoreAudioApi.DataFlow.Render; NAudio.Wave.IWaveIn dev = isPlay ? new NAudio.Wave.WasapiLoopbackCapture(mm) : new NAudio.CoreAudioApi.WasapiCapture(mm); if (dev != null) { wf = dev.WaveFormat; makeSerializationData(); dev.Dispose(); return(true); } } catch (System.Runtime.InteropServices.COMException) { mm = null; } return(false); }
private int GetNAudioMasterPeakValue(NAudio.CoreAudioApi.MMDevice device) { int result = 0; if (device == null) { goto emptyReturn; } try { result = (int)(Math.Round(device.AudioMeterInformation.MasterPeakValue * 100)); return(result); } catch (Exception) { goto emptyReturn; } emptyReturn: return(0); }
public bool test() { tested = true; wf = null; try { if (mm == null) { return(false); } NAudio.Wave.IWaveIn dev = null; capt1 = mm.FriendlyName; // windows name capt2 = mm.DeviceFriendlyName; // just device if (capt1.EndsWith(capt2 + ")")) { capt1 = capt1.Substring(0, capt1.Length - (capt2.Length + 3)); } isRec = mm.DataFlow == NAudio.CoreAudioApi.DataFlow.All || mm.DataFlow == NAudio.CoreAudioApi.DataFlow.Capture; isPlay = mm.DataFlow == NAudio.CoreAudioApi.DataFlow.All || mm.DataFlow == NAudio.CoreAudioApi.DataFlow.Render; dev = isPlay ? dev = new NAudio.Wave.WasapiLoopbackCapture(mm) : dev = new NAudio.CoreAudioApi.WasapiCapture(mm); if (dev != null) { wf = dev.WaveFormat; makeSerializationData(); dev.Dispose(); return(true); } } catch { mm = null; } return(false); }
private void SourceStreamDataAvailable(object sender, WaveInEventArgs e) { NAudio.CoreAudioApi.MMDeviceEnumerator MMDE = new NAudio.CoreAudioApi.MMDeviceEnumerator(); NAudio.CoreAudioApi.MMDeviceCollection DevCol = MMDE.EnumerateAudioEndPoints(NAudio.CoreAudioApi.DataFlow.All, NAudio.CoreAudioApi.DeviceState.Active); NAudio.CoreAudioApi.MMDevice device = DevCol[3]; double volume = Math.Round(device.AudioMeterInformation.MasterPeakValue * 100, 1); Console.WriteLine(volume.ToString()); if (waveWriter == null) { return; } if (volume < 1) { counter++; } else { waveWriter.Write(e.Buffer, 0, e.BytesRecorded); waveWriter.Flush(); counter = 0; mCounter++; } if (counter > 30) { long a1 = sw.ElapsedMilliseconds; int c = mCounter; counter = 0; sourceStream.DataAvailable -= this.SourceStreamDataAvailable; StopRecording(); eventStopRecording(this, new EventArgs()); } }
public override void Process(StreamDeckSharp.IStreamDeck deck) { if (baseBitMap == null) { baseBitMap = (Bitmap)Bitmap.FromFile("Speaker.bmp"); } Bitmap tempBitmap = new Bitmap(baseBitMap.Width, baseBitMap.Height); if (dev == null) { NAudio.CoreAudioApi.MMDeviceEnumerator enu = new NAudio.CoreAudioApi.MMDeviceEnumerator(); var devices = enu.EnumerateAudioEndPoints(NAudio.CoreAudioApi.DataFlow.Render, NAudio.CoreAudioApi.DeviceState.All); foreach (var d in devices) { try { if (d.FriendlyName == OutputDeviceName) { dev = d; break; } } catch (Exception exc) { } } } if (dev != null) { try { //"XSplit Stream Audio Renderer") { if (base.enabled) { int pct = (int)(Math.Round(dev.AudioMeterInformation.MasterPeakValue * 100)); Console.Write(""); System.Drawing.Brush GreenPen = new SolidBrush(Color.Green); System.Drawing.Brush YellowPen = new SolidBrush(Color.Yellow); System.Drawing.Brush RedPen = new SolidBrush(Color.Red); using (var graph = Graphics.FromImage(tempBitmap)) { graph.DrawImage(baseBitMap, 0, 0); int properWith = 72 * pct / 100; if (pct > 95) { graph.FillRectangle(RedPen, 0, 0, properWith, 72 - 0); } else { if (pct > 75) { graph.FillRectangle(YellowPen, 0, 0, properWith, 72 - 0); } else { graph.FillRectangle(GreenPen, 0, 0, properWith, 72 - 0); } } } theBitmap = tempBitmap; } } } catch (Exception exc) { } } }
/// <summary> /// Метод события до загрузки формы /// </summary> /// <param name="sender">отправитель</param> /// <param name="e">параметры</param> private void Form1_Load(object sender, EventArgs e) { try { #region Инициализация переменных и чтение параметров из конфигурационного файла this.Text = "VolumeLight " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); connected = false; states = new List <State>(10); for (int i = 0; i < 10; i++) { states.Add(new State(i + 1, Color.Black)); } period = 1; start = 5; end = 105; host = "127.0.0.1"; port = 3636; System.IO.StreamReader sr = new System.IO.StreamReader("config"); while (!sr.EndOfStream) { string line = sr.ReadLine(); if (line.IndexOf("led") > -1) { int lednumber = Int32.Parse(line.Substring(3, line.IndexOf("=") - 3)); line = line.Substring(line.IndexOf("=") + 1); int position = Int32.Parse(line.Substring(0, line.IndexOf("|"))); string color = line.Substring(line.IndexOf("|") + 1, line.Length - line.IndexOf("|") - 1); states[lednumber - 1] = new State(position, color); } if (line.IndexOf("period") > -1) { period = Int32.Parse(line.Substring(line.IndexOf("=") + 1, line.Length - line.IndexOf("=") - 1)); } if (line.IndexOf("start") > -1) { start = Int32.Parse(line.Substring(line.IndexOf("=") + 1, line.Length - line.IndexOf("=") - 1)); } if (line.IndexOf("end") > -1) { end = Int32.Parse(line.Substring(line.IndexOf("=") + 1, line.Length - line.IndexOf("=") - 1)); } if (line.IndexOf("host") > -1) { host = line.Substring(line.IndexOf("=") + 1, line.Length - line.IndexOf("=") - 1); } if (line.IndexOf("port") > -1) { port = Int32.Parse(line.Substring(line.IndexOf("=") + 1, line.Length - line.IndexOf("=") - 1)); } } sr.Close(); en = new NAudio.CoreAudioApi.MMDeviceEnumerator(); mmdevice = en.GetDefaultAudioEndpoint(NAudio.CoreAudioApi.DataFlow.Render, NAudio.CoreAudioApi.Role.Multimedia); api = new ApiLightpack(); numericUpDown2.Value = period; numericUpDown3.Value = start; numericUpDown4.Value = end; textBox1.Text = host; numericUpDown1.Value = port; label_1.Text = states[0].Position.ToString(); label_2.Text = states[1].Position.ToString(); label_3.Text = states[2].Position.ToString(); label_4.Text = states[3].Position.ToString(); label_5.Text = states[4].Position.ToString(); label_6.Text = states[5].Position.ToString(); label_7.Text = states[6].Position.ToString(); label_8.Text = states[7].Position.ToString(); label_9.Text = states[8].Position.ToString(); label_10.Text = states[9].Position.ToString(); timer1.Interval = period; #endregion //Запуск таймера timer1.Enabled = true; } catch (Exception ex) { MessageBox.Show("Сообщение: " + ex.Message + Environment.NewLine + "StackTrace: " + Environment.NewLine + ex.StackTrace, "Произошла ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); } }
private void cbDevice_SelectedIndexChanged(object sender, EventArgs e) { master = (NAudio.CoreAudioApi.MMDevice)cbDevice.Items[cbDevice.SelectedIndex]; }
// ctor, constructor /// <exception cref="InitFailure">When initialization fails in a way that can not be continued from.</exception> public MicManager() { System.Diagnostics.Debug.Assert(Taskmaster.IsMainThread(), "Requires main thread"); // Target = Maximum; // superfluous; CLEANUP var stats = Taskmaster.Config.Load(statfile); // there should be easier way for this, right? Corrections = (stats.Config.Contains("Statistics") && stats.Config["Statistics"].Contains("Corrections")) ? stats.Config["Statistics"]["Corrections"].IntValue : 0; // DEVICES // find control interface // FIXME: Deal with multiple recording devices. var waveInDeviceNumber = IntPtr.Zero; // 0 is default or first? NAudio.Mixer.MixerLine mixerLine = null; try { mixerLine = new NAudio.Mixer.MixerLine(waveInDeviceNumber, 0, NAudio.Mixer.MixerFlags.WaveIn); } catch (NAudio.MmException ex) { Log.Fatal("<Microphone> Default device not found."); throw new InitFailure("Failed to get default microphone device.", ex); } Control = (NAudio.Mixer.UnsignedMixerControl)mixerLine.Controls.FirstOrDefault( (control) => control.ControlType == NAudio.Mixer.MixerControlType.Volume ); if (Control == null) { Log.Error("<Microphone> No volume control acquired!"); throw new InitFailure("Mic monitor control not acquired."); } _volume = Control.Percent; // get default communications device var mm_enum = new NAudio.CoreAudioApi.MMDeviceEnumerator(); m_dev = mm_enum?.GetDefaultAudioEndpoint(NAudio.CoreAudioApi.DataFlow.Capture, NAudio.CoreAudioApi.Role.Communications); if (m_dev != null) { m_dev.AudioEndpointVolume.OnVolumeNotification += VolumeChangedHandler; } mm_enum = null; // unnecessary? if (m_dev == null) { Log.Error("<Microphone> No communications device found!"); throw new InitFailure("No communications device found"); } var mvol = "Microphone volume"; var corecfg = Taskmaster.Config.Load(Taskmaster.coreconfig); var save = false || !corecfg.Config["Media"].Contains(mvol); var defaultvol = corecfg.Config["Media"].GetSetDefault(mvol, 100d).DoubleValue; if (save) { corecfg.MarkDirty(); } var fname = "Microphone.Devices.ini"; var vname = "Volume"; var devcfg = Taskmaster.Config.Load(fname); var guid = (m_dev.ID.Split('}'))[1].Substring(2); var devname = m_dev.DeviceFriendlyName; var unset = !(devcfg.Config[guid].Contains(vname)); var devvol = devcfg.Config[guid].GetSetDefault(vname, defaultvol).DoubleValue; devcfg.Config[guid]["Name"].StringValue = devname; if (unset) { devcfg.Save(); } Target = devvol.Constrain(0, 100); Log.Information("<Microphone> Default device: {Device} (volume: {TargetVolume:N1}%)", m_dev.FriendlyName, Target); Volume = Target; Log.Information("<Microphone> Component loaded."); }
public void UpdateDeviceInfo() { inDeviceInfo = new List<DeviceInfo>(); outDeviceInfo = new List<DeviceInfo>(); // Get devices for in and out List<WaveInCapabilities> inDevCaps = new List<WaveInCapabilities>(); int waveInDevices = WaveIn.DeviceCount; for (int waveInDevice = 0; waveInDevice < waveInDevices; waveInDevice++) { WaveInCapabilities devCaps = WaveIn.GetCapabilities(waveInDevice); inDevCaps.Add(devCaps); logger.Info("AudioDevices::UpdateDeviceInfo Device {0}: {1}, {2} channels", waveInDevice, devCaps.ProductName, devCaps.Channels); } List<WaveOutCapabilities> outDevCaps = new List<WaveOutCapabilities>(); int waveOutDevices = WaveOut.DeviceCount; for (int waveOutDevice = 0; waveOutDevice < waveOutDevices; waveOutDevice++) { WaveOutCapabilities devCaps = WaveOut.GetCapabilities(waveOutDevice); outDevCaps.Add(devCaps); logger.Info("AudioDevices::UpdateDeviceInfo Device {0}: {1}, {2} channels", waveOutDevice, devCaps.ProductName, devCaps.Channels); } // Now go through MM devices to match up try { //Instantiate an Enumerator to find audio devices NAudio.CoreAudioApi.MMDeviceEnumerator MMDE = new NAudio.CoreAudioApi.MMDeviceEnumerator(); //Get all the devices, no matter what condition or status NAudio.CoreAudioApi.MMDeviceCollection DevCol = MMDE.EnumerateAudioEndPoints(NAudio.CoreAudioApi.DataFlow.All, NAudio.CoreAudioApi.DeviceState.All); //Loop through all devices foreach (NAudio.CoreAudioApi.MMDevice dev in DevCol) { try { for (int idx = 0; idx < inDevCaps.Count; idx++) if (DevicesMatch(inDevCaps[idx].ProductName, dev.FriendlyName)) { DeviceInfo devInfo = new DeviceInfo(); devInfo.waveDeviceNumber = idx; devInfo.deviceName = dev.FriendlyName; devInfo.deviceId = dev.ID; devInfo.waveInCaps = inDevCaps[idx]; inDeviceInfo.Add(devInfo); if (_curInDevice == null) { _curInDevice = dev; _curWaveInDeviceInfoIdx = inDeviceInfo.Count - 1; } } for (int idx = 0; idx < outDevCaps.Count; idx++) if (DevicesMatch(outDevCaps[idx].ProductName, dev.FriendlyName)) { DeviceInfo devInfo = new DeviceInfo(); devInfo.waveDeviceNumber = idx; devInfo.deviceName = dev.FriendlyName; devInfo.deviceId = dev.ID; devInfo.waveOutCaps = outDevCaps[idx]; outDeviceInfo.Add(devInfo); bool bUseThis = false; if (_curOutDevice == null) bUseThis = true; else if (!_curOutDevice.FriendlyName.Contains("Speakers") && dev.FriendlyName.Contains("Speakers")) bUseThis = true; if (bUseThis) { _curOutDevice = dev; _curWaveOutDeviceInfoIdx = outDeviceInfo.Count - 1; } } } catch (Exception ex) { //Do something with exception when an audio endpoint could not be muted logger.Error("AudioDevices::UpdateDeviceInfo Exception in Update {0}", ex.Message); } } } catch (Exception ex) { //When something happend that prevent us to iterate through the devices logger.Error("AudioDevices::UpdateDeviceInfo Could not enumerate devices due to an excepion: {0}", ex.Message); } }
public PlaybackRecorder(NAudio.CoreAudioApi.MMDevice device) { capture = new NAudio.Wave.WasapiLoopbackCapture(device); capture.DataAvailable += capture_DataAvailable; }
/// <summary> /// Метод события до загрузки формы /// </summary> /// <param name="sender">отправитель</param> /// <param name="e">параметры</param> private void Form1_Load(object sender, EventArgs e) { try { #region Инициализация переменных и чтение параметров из конфигурационного файла this.Text = "VolumeLight " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); connected = false; states = new List<State>(10); for (int i = 0; i < 10; i++) { states.Add(new State(i + 1, Color.Black)); } period = 1; start = 5; end = 105; host = "127.0.0.1"; port = 3636; System.IO.StreamReader sr = new System.IO.StreamReader("config"); while (!sr.EndOfStream) { string line = sr.ReadLine(); if (line.IndexOf("led") > -1) { int lednumber = Int32.Parse(line.Substring(3, line.IndexOf("=") - 3)); line = line.Substring(line.IndexOf("=") + 1); int position = Int32.Parse(line.Substring(0, line.IndexOf("|"))); string color = line.Substring(line.IndexOf("|") + 1, line.Length - line.IndexOf("|") - 1); states[lednumber - 1] = new State(position, color); } if (line.IndexOf("period") > -1) { period = Int32.Parse(line.Substring(line.IndexOf("=") + 1, line.Length - line.IndexOf("=") - 1)); } if (line.IndexOf("start") > -1) { start = Int32.Parse(line.Substring(line.IndexOf("=") + 1, line.Length - line.IndexOf("=") - 1)); } if (line.IndexOf("end") > -1) { end = Int32.Parse(line.Substring(line.IndexOf("=") + 1, line.Length - line.IndexOf("=") - 1)); } if (line.IndexOf("host") > -1) { host = line.Substring(line.IndexOf("=") + 1, line.Length - line.IndexOf("=") - 1); } if (line.IndexOf("port") > -1) { port = Int32.Parse(line.Substring(line.IndexOf("=") + 1, line.Length - line.IndexOf("=") - 1)); } } sr.Close(); en = new NAudio.CoreAudioApi.MMDeviceEnumerator(); mmdevice = en.GetDefaultAudioEndpoint(NAudio.CoreAudioApi.DataFlow.Render, NAudio.CoreAudioApi.Role.Multimedia); api = new ApiLightpack(); numericUpDown2.Value = period; numericUpDown3.Value = start; numericUpDown4.Value = end; textBox1.Text = host; numericUpDown1.Value = port; label_1.Text = states[0].Position.ToString(); label_2.Text = states[1].Position.ToString(); label_3.Text = states[2].Position.ToString(); label_4.Text = states[3].Position.ToString(); label_5.Text = states[4].Position.ToString(); label_6.Text = states[5].Position.ToString(); label_7.Text = states[6].Position.ToString(); label_8.Text = states[7].Position.ToString(); label_9.Text = states[8].Position.ToString(); label_10.Text = states[9].Position.ToString(); timer1.Interval = period; #endregion //Запуск таймера timer1.Enabled = true; } catch (Exception ex) { MessageBox.Show("Сообщение: " + ex.Message + Environment.NewLine + "StackTrace: " + Environment.NewLine + ex.StackTrace, "Произошла ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); } }