/// <summary> /// Construct a new voice loopback session. /// </summary> /// <param name="codec">An audio codec to encode and decode with.</param> /// <param name="quality">The encoding quality (usually the sample rate).</param> public VoiceLoopback(VoiceCodec codec, int quality) { var info = new CodecInfo(codec, quality); _waveIn = new WaveIn(this, info.DecodedFormat, info.DecodedBufferSize); _waveOut = new WaveOut(this, info.EncodedFormat, info.EncodedBufferSize); _encoder = new AudioConverter(info.DecodedBufferSize, info.DecodedFormat, info.EncodedFormat); }
public WaveOutBuffer(WaveOut waveOut, int bufferSize) { if (waveOut == null) throw new ArgumentNullException("waveOut"); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize"); _waveOut = waveOut; _bufferSize = bufferSize; }
/// <summary> /// Default constructor. /// </summary> /// <param name="device">Audio aoutput device.</param> /// <param name="samplesPerSec">Sample rate, in samples per second (hertz).</param> /// <param name="bitsPerSample">Bits per sample. For PCM 8 or 16 are the only valid values.</param> /// <param name="channels">Number of channels.</param> /// <exception cref="ArgumentNullException">Is raised when <b>device</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public AudioOut(AudioOutDevice device,int samplesPerSec,int bitsPerSample,int channels) { if(device == null){ throw new ArgumentNullException("device"); } if(samplesPerSec < 1){ throw new ArgumentException("Argument 'samplesPerSec' value must be >= 1.","samplesPerSec"); } if(bitsPerSample < 8){ throw new ArgumentException("Argument 'bitsPerSample' value must be >= 8.","bitsPerSample"); } if(channels < 1){ throw new ArgumentException("Argument 'channels' value must be >= 1.","channels"); } m_pDevice = device; m_SamplesPerSec = samplesPerSec; m_BitsPerSample = bitsPerSample; m_Channels = channels; m_pWaveOut = new WaveOut(device,samplesPerSec,bitsPerSample,channels); }
public FilePlayer(string fileName) { var fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); var sig = new byte[4]; try { fileStream.Read(sig, 0, 4); fileStream.Seek(0, SeekOrigin.Begin); if (WavFileSignature.SequenceEqual(sig.Take(WavFileSignature.Length))) { var wavStream = new WavFileStream(fileStream); _waveOut = new WaveOut(wavStream, wavStream.Format, WavBufferSamples * wavStream.Format.FrameSize); } else if (Mp3FileSignature.SequenceEqual(sig.Take(Mp3FileSignature.Length))) { var mp3Stream = new Mp3FileStream(fileStream); _waveOut = new WaveOut(mp3Stream, mp3Stream.Format, mp3Stream.Format.BlockSize + 1); } else { throw new FileFormatException("Unrecognized file format."); } } catch (EndOfStreamException) { throw new FileFormatException("Premature end of file."); } _waveOut.EndOfStream += (sender, e) => { var handler = this.Done; if(handler != null) { handler(this, EventArgs.Empty); } }; }
/// <summary> /// Default constructor. /// </summary> /// <param name="device">Audio output device.</param> /// <param name="samplesPerSec">Sample rate, in samples per second (hertz).</param> /// <param name="bitsPerSample">Bits per sample. For PCM 8 or 16 are the only valid values.</param> /// <param name="channels">Number of channels.</param> /// <exception cref="ArgumentNullException">Is raised when <b>device</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public AudioOut(AudioOutDevice device, int samplesPerSec, int bitsPerSample, int channels) { if (device == null) { throw new ArgumentNullException("device"); } if (samplesPerSec < 1) { throw new ArgumentException("Argument 'samplesPerSec' value must be >= 1.", "samplesPerSec"); } if (bitsPerSample < 8) { throw new ArgumentException("Argument 'bitsPerSample' value must be >= 8.", "bitsPerSample"); } if (channels < 1) { throw new ArgumentException("Argument 'channels' value must be >= 1.", "channels"); } m_pDevice = device; m_pAudioFormat = new AudioFormat(samplesPerSec, bitsPerSample, channels); m_pWaveOut = new WaveOut(device, samplesPerSec, bitsPerSample, channels); }
public static void PlayMedia() { OpenFileDialog ofd = new OpenFileDialog(); ofd.CheckFileExists = true; ofd.Filter = "mp3 file|*.mp3"; DialogResult result = ofd.ShowDialog(); if (result.ToString() != "OK") { Console.WriteLine("Please select a File."); return; } Mp3FileReader reader = new Mp3FileReader(ofd.FileName); WaveOut wavOut = new WaveOut(); wavOut.Init(reader); wavOut.Play(); while (true) { Console.WriteLine("Status: {0}, Time: {1}", wavOut.PlaybackState, wavOut.GetPositionTimeSpan().TotalMilliseconds.ToString()); Thread.Sleep(1000); } }
private void BtnReproducir_Click(object sender, RoutedEventArgs e) { if (output != null && output.PlaybackState == PlaybackState.Paused) { //Retomo la reproduccion output.Play(); btnReproducir.IsEnabled = false; btnPausa.IsEnabled = true; btnDetener.IsEnabled = true; } else { if (txtRutaArchivo.Text != null && txtRutaArchivo.Text != string.Empty) { reader = new AudioFileReader(txtRutaArchivo.Text); volume = new VolumeSampleProvider(reader); volume.Volume = (float)(sldVolumen.Value); output = new WaveOut(); output.DeviceNumber = cbDispositivoSalida.SelectedIndex; output.PlaybackStopped += Output_PlaybackStopped; output.Init(volume); output.Play(); //Cambiar el volumen del output //output.Volume = (float)(sldVolumen.Value); btnReproducir.IsEnabled = false; btnDetener.IsEnabled = true; btnPausa.IsEnabled = true; sldTiempo.Maximum = reader.TotalTime.TotalSeconds; lblTiempoTotal.Text = reader.TotalTime.ToString().Substring(0, 8); lblTiempoActual.Text = reader.CurrentTime.ToString().Substring(0, 8); timer.Start(); } } }
public void Open() { if (InSample == null) { throw new InvalidOperationException("In Sample is not set."); } if (DataRequired == null) { throw new InvalidOperationException("DataRequired event is not subscribed to."); } Format outFormat = new Format( InSample.SampleRate, 4, InSample.Channels); OutSample = null; OutFormat = outFormat; m_waveProvider = new WaveProvider(DataRequired, this); m_waveOutPlayer = new WaveOut(); m_waveOutPlayer.NumberOfBuffers = 2; m_waveOutPlayer.DesiredLatency = m_desiredLatencyInMs; m_waveOutPlayer.PlaybackStopped += WaveOut_PlaybackStopped; Latency = m_desiredLatencyInMs * m_bytesPerSample * OutFormat.Channels * OutFormat.SampleRate / 1000; m_waveOutPlayer.Init(m_waveProvider); IsOpen = true; }
private void RebelSettings_Load(object sender, EventArgs e) { Utils.settingsOpened = true; Settings.Default.Reload(); if (Settings.Default.PushToTalk) { radioButton4.Checked = true; } if (!Settings.Default.StereoAudio) { radioButton1.Checked = true; } numericUpDown1.Value = Settings.Default.FrequencyRate; numericUpDown2.Value = Settings.Default.AudioBits; comboBox1.Items.Add("Default"); comboBox2.Items.Add("Default"); for (int waveInDevice = 0; waveInDevice < WaveIn.DeviceCount; waveInDevice++) { comboBox1.Items.Add(WaveIn.GetCapabilities(waveInDevice).ProductName); } for (int waveOutDevice = 0; waveOutDevice < WaveOut.DeviceCount; waveOutDevice++) { comboBox2.Items.Add(WaveOut.GetCapabilities(waveOutDevice).ProductName); } try { if (comboBox1.Items[Settings.Default.InputDevice].ToString() == Settings.Default.InputDeviceName) { comboBox1.SelectedIndex = Settings.Default.InputDevice; } else { comboBox1.SelectedIndex = 0; } } catch (Exception ex) { comboBox1.SelectedIndex = 0; } try { if (comboBox2.Items[Settings.Default.OutputDevice].ToString() == Settings.Default.OutputDeviceName) { comboBox2.SelectedIndex = Settings.Default.OutputDevice; } else { comboBox2.SelectedIndex = 0; } } catch (Exception ex) { comboBox2.SelectedIndex = 0; } uint CurrVol = 0; waveOutGetVolume(IntPtr.Zero, out CurrVol); trackBar1.Value = (ushort)(CurrVol & 0x0000ffff) / (ushort.MaxValue / 100); materialLabel6.Text = "Application volume (" + trackBar1.Value.ToString() + "/100):"; try { textBox1.Text = ((new KeysConverter()).ConvertTo(Settings.Default.PushToTalkKey, typeof(string))).ToString().Replace("None", ","); } catch (Exception ex) { } }
public static void PlayPS4Sound(Sound Soundtoplay) { try { if (Properties.Settings.Default.EnableMusic == false) { return; } switch (Soundtoplay) { case Sound.Notification: { new Thread(() => { //set the thread as a background worker Thread.CurrentThread.IsBackground = true; IWavePlayer waveOutDevice = new WaveOut(); WaveStream mp3file = CreateInputStream(Properties.Resources.PS4_Notification); TimeSpan ts = mp3file.TotalTime; waveOutDevice.Init(mp3file); waveOutDevice.Volume = 0.7f; waveOutDevice.Play(); /* run your code here */ Thread.Sleep(ts); waveOutDevice.Dispose(); waveOutDevice.Stop(); }).Start(); } break; case Sound.Error: { new Thread(() => { //set the thread as a background worker Thread.CurrentThread.IsBackground = true; IWavePlayer waveOutDevice = new WaveOut(); WaveStream mp3file = CreateInputStream(Properties.Resources.Ps4_Error_Sound); TimeSpan ts = mp3file.TotalTime; waveOutDevice.Init(mp3file); waveOutDevice.Volume = 0.5f; waveOutDevice.Play(); /* run your code here */ Thread.Sleep(ts); waveOutDevice.Dispose(); waveOutDevice.Stop(); }).Start(); } break; case Sound.Shutdown: { WaveStream mp3file = CreateInputStream(Properties.Resources.PS4_Shutdown); TimeSpan ts = mp3file.TotalTime; waveOutDevice.Init(mp3file); waveOutDevice.Volume = 0.5f; waveOutDevice.Play(); new Thread(() => { Thread.CurrentThread.IsBackground = true; /* run your code here */ Thread.Sleep(ts); waveOutDevice.Stop(); //waveOutDevice.Dispose(); }).Start(); } break; case Sound.PS4_Info_Pannel_Sound: { new Thread(() => { //set the thread as a background worker Thread.CurrentThread.IsBackground = true; IWavePlayer waveOutDevice = new WaveOut(); WaveStream mp3file = CreateInputStream(Properties.Resources.PS4_Notification); TimeSpan ts = mp3file.TotalTime; waveOutDevice.Init(mp3file); waveOutDevice.Volume = 0.5f; waveOutDevice.Play(); Thread.Sleep(ts); waveOutDevice.Stop(); }).Start(); break; } case Sound.Options: { WaveStream mp3file = CreateInputStream(Properties.Resources.PS4_Options_Pannel); TimeSpan ts = mp3file.TotalTime; waveOutDevice.Init(mp3file); waveOutDevice.Volume = 0.5f; waveOutDevice.Play(); new Thread(() => { Thread.CurrentThread.IsBackground = true; /* run your code here */ Thread.Sleep(ts); waveOutDevice.Stop(); //waveOutDevice.Dispose(); }).Start(); break; } case Sound.Navigation: { new Thread(() => { Thread.CurrentThread.IsBackground = true; IWavePlayer waveOutDevice = new WaveOut(); WaveStream mp3file = CreateInputStream(Properties.Resources.PS4_Navigation_Sound); TimeSpan ts = mp3file.TotalTime; waveOutDevice.Init(mp3file); waveOutDevice.Volume = 0.5f; waveOutDevice.Play(); /* run your code here */ Thread.Sleep(ts); waveOutDevice.Stop(); //waveOutDevice.Dispose(); }).Start(); break; } case Sound.PS4_Music: { WaveStream mp3file = CreateInputStream(Properties.Resources.ps4BGM); ////PS4BGMDevice = new AsioOut("ASIO4ALL v2"); ////PS4BGMDevice.Init(mp3file); ////PS4BGMDevice.Play(); TimeSpan ts = mp3file.TotalTime; PS4BGMDevice.Init(mp3file); PS4BGMDevice.Volume = 0.5f; PS4BGMDevice.Play(); } break; case Sound.LQ: { WaveStream mp3file = CreateInputStream(Properties.Resources.lq); ////PS4BGMDevice = new AsioOut("ASIO4ALL v2"); ////PS4BGMDevice.Init(mp3file); ////PS4BGMDevice.Play(); TimeSpan ts = mp3file.TotalTime; PS4BGMDevice.Init(mp3file); PS4BGMDevice.Volume = 0.5f; PS4BGMDevice.Play(); } break; case Sound.sk: { WaveStream mp3file = CreateInputStream(Properties.Resources.dovahkiin); ////PS4BGMDevice = new AsioOut("ASIO4ALL v2"); ////PS4BGMDevice.Init(mp3file); ////PS4BGMDevice.Play(); TimeSpan ts = mp3file.TotalTime; PS4BGMDevice.Init(mp3file); PS4BGMDevice.Volume = 0.5f; PS4BGMDevice.Play(); } break; case Sound.pete: { WaveStream mp3file = CreateInputStream(Properties.Resources.priates); ////PS4BGMDevice = new AsioOut("ASIO4ALL v2"); ////PS4BGMDevice.Init(mp3file); ////PS4BGMDevice.Play(); TimeSpan ts = mp3file.TotalTime; PS4BGMDevice.Init(mp3file); PS4BGMDevice.Volume = 0.5f; PS4BGMDevice.Play(); } break; default: break; } } catch (Exception ex) { //encolsed the entire sound class to not crash on issue #13 //it will still break but atleast the application should not crash } }
public void AudioCommand(string command) { Logger.Info(command + " received"); lock (lockObject) { switch (command) { case "play": PlaySound(playlist.NowPlaying()); break; case "pause": output.Pause(); break; case "resume": output.Play(); break; case "stop": output.PlaybackStopped -= output_PlaybackStopped; output.Stop(); break; case "skip": output.PlaybackStopped -= output_PlaybackStopped; PlaySound(playlist.NextSong()); break; case "prev": output.PlaybackStopped -= output_PlaybackStopped; PlaySound(playlist.PrevSong()); break; case "pausePlayResume": if (output == null || output.PlaybackState == PlaybackState.Stopped) { Logger.Info("stopped to play"); PlaySound(playlist.NowPlaying()); } else if (output.PlaybackState == PlaybackState.Playing) { Logger.Info("playing to pause"); output.Pause(); } else if (output.PlaybackState == PlaybackState.Paused) { Logger.Info("paused to resume"); output.Play(); } break; case "refreshSongList": playlist.Refresh(); break; case "getPosition": Logger.Info(stream.Position); break; case "getLength": Logger.Info(stream.Length); break; case "getDeviceInfo": for (int i = 0; i < WaveOut.DeviceCount; ++i) { Logger.Info(i + " " + WaveOut.GetCapabilities(i).ProductName); } break; case "RollVolumeUp": break; case "RollVolumeDown": break; } } Logger.Info(command + " executed"); }
private void receiveSoundCaptureToolStripMenuItem_Click(object sender, EventArgs e) { var selectedItem = listUsers.SelectedItem; if (selectedItem == null) { return; } string selectedUser = selectedItem.ToString(); int pos = selectedUser.LastIndexOf(" - "); if (pos > 0) { selectedUser = selectedUser.Substring(0, pos); } lock (fWaveOutsByClient) { var fastEnumerator = fWaveOutsByClient.GetValueOrDefault(selectedUser); if (fastEnumerator != null) { fastEnumerator.Dispose(); fWaveOutsByClient.Remove(selectedUser); return; } try { if (selectedUser == fNickName) { fastEnumerator = SoundEnumerator.Distributor.CreateClient(); } else { fastEnumerator = fClient.ReceiveSound(selectedUser); } if (fastEnumerator == null) { return; } var outDevices = WaveOut.Devices; if (outDevices.Length == 0) { MessageBox.Show("There are no output sound devices installed."); return; } var outDevice = outDevices[0]; var waveOut = new WaveOut(outDevice, 8000, 16, 1); fWaveOutsByClient.Add(selectedUser, fastEnumerator); UnlimitedThreadPool.Run ( () => { try { while (true) { byte[] buffer = fastEnumerator.GetNext(); if (buffer == null) { return; } waveOut.Play(buffer, 0, buffer.Length); } } catch { } } ); } catch { if (fastEnumerator != null) { try { fastEnumerator.Dispose(); } catch { } } } return; } }
public void Stop() { output?.Stop(); output = null; }
protected override void PlayAndRecord(string WavFileName, Channel Channel) { bool IsEqual = false; ProductName = string.Empty; List <Guid> AudioDeviceList = null; SetupApi = new SetupApi(); di.Clear(); switch (Channel) { case Channel.Left: case Channel.Right: case Channel.AudioJack: AudioDeviceList = MachineAudioDeviceList; break; case Channel.HeadSet: AudioDeviceList = ExternalAudioDeviceList; break; case Channel.Fan: AudioDeviceList = FanRecordDeviceList; break; } for (int n = -1; n < WaveOut.DeviceCount; n++) { var caps = WaveOut.GetCapabilities(n); Console.WriteLine("Play device {0}: {1}", n, caps.ProductName); Console.WriteLine(caps.ManufacturerGuid); Trace.WriteLine(caps.ManufacturerGuid); foreach (var v in AudioDeviceList) { if (caps.ManufacturerGuid.Equals(v)) { DeviceNumber = n; ProductName = caps.ProductName; SetupApi.GetLocationInformation(DeviceNumber, ProductName); Console.WriteLine("Find"); } } } switch (Channel) { case Channel.Left: case Channel.Right: if (string.IsNullOrEmpty(ProductName)) { throw new Exception("Machine audio device not found"); } break; case Channel.HeadSet: IsEqual = ExternalAudioDeviceList.Except(FanRecordDeviceList).Count() == 0; if (IsEqual) { if (SetupApi.di.Count() < 2 || ProductName.Contains(UsbAudioDeviceName)) { throw new Exception("External audio device not found"); } } else { if (string.IsNullOrEmpty(ProductName) || ProductName.Contains(UsbAudioDeviceName)) { throw new Exception("External audio device not found"); } } DeviceNumber = SetupApi.di.OrderBy(e => e.Value).FirstOrDefault().Key; //ProductName = SetupApi.di.OrderBy(e => e.Value).FirstOrDefault().Value; break; case Channel.AudioJack: if (string.IsNullOrEmpty(ProductName)) { throw new Exception("Audio Jack device not found"); } break; case Channel.Fan: IsEqual = ExternalAudioDeviceList.Except(FanRecordDeviceList).Count() == 0; if (IsEqual) { if (SetupApi.di.Count() < 2 || ProductName.Contains(UsbAudioDeviceName)) { throw new Exception("Fan record device not found"); } } else { if (string.IsNullOrEmpty(ProductName) || ProductName.Contains(UsbAudioDeviceName)) { throw new Exception("Fan record device not found"); } } DeviceNumber = SetupApi.di.OrderBy(e => e.Value).LastOrDefault().Key; //ProductName = SetupApi.di.OrderBy(e => e.Value).LastOrDefault().Value; break; } using (var inputReader = new WaveFileReader(WavFileName)) using (var outputDevice = new WaveOutEvent()) { outputDevice.DeviceNumber = DeviceNumber; Console.WriteLine("Play device: ###### {0} ######", WaveOut.GetCapabilities(DeviceNumber).ProductName); foreach (var item in SetupApi.di.OrderBy(e => e.Value)) { Console.WriteLine(item.Key + " " + item.Value); } outputDevice.Init(inputReader); outputDevice.PlaybackStopped += (sender, e) => { if (WavSource != null) { WavSource.StopRecording(); } Console.WriteLine("Play Stopped"); }; outputDevice.Play(); switch (Channel) { case Channel.Left: Record(Channel.Left).Wait(); break; case Channel.Right: Record(Channel.Right).Wait(); break; case Channel.AudioJack: Record(Channel.AudioJack).Wait(); break; case Channel.HeadSet: Record(Channel.HeadSet).Wait(); break; case Channel.Fan: Record(Channel.Fan).Wait(); break; } while (outputDevice.PlaybackState == PlaybackState.Playing) { Thread.Sleep(500); } } }
public void PlayMp3FromUrl(string url) { new Thread(delegate(object o) { var request = (HttpWebRequest)WebRequest.Create(url); request.CookieContainer = cookie; request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko"; request.Method = "GET"; request.Accept = "text/html"; request.AllowAutoRedirect = true; request.Timeout = 15000; request.ReadWriteTimeout = 15000; try { var response = request.GetResponse(); using (var stream = response.GetResponseStream()) { var buffer = new byte[65536]; // 64KB chunks int read; while (stream != null && (read = stream.Read(buffer, 0, buffer.Length)) > 0) { var pos = _ms.Position; _ms.Position = _ms.Length; _ms.Write(buffer, 0, read); _ms.Position = pos; } } } catch (WebException) { Debug.WriteLine("Error retriving or playing stream"); if (SongComplete != null) { SongComplete(); } } }).Start(); // Pre-buffering some data to allow NAudio to start playing while (_ms.Length < 65536 * 10) { Thread.Sleep(1000); } _ms.Position = 0; try { using ( _blockAlignedStream = new BlockAlignReductionStream(WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(_ms))) ) { using (var waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback())) { waveOut.DeviceNumber = _device; waveOut.Init(_blockAlignedStream); waveOut.Play(); while (waveOut.PlaybackState != PlaybackState.Stopped) { if (GetVolume != null) { waveOut.Volume = GetVolume(); } // Debug.WriteLine(GetVolume()); if (_shouldStop) { waveOut.Stop(); } if (_isPaused) { waveOut.Pause(); } if (!_isPaused) { waveOut.Resume(); } if (waveOut.PlaybackState == PlaybackState.Playing) { Thread.Sleep(100); } SongCurrTime?.Invoke(_blockAlignedStream.CurrentTime.TotalSeconds); if (waveOut.PlaybackState == PlaybackState.Paused) { Thread.Sleep(1000); } } if (waveOut.PlaybackState == PlaybackState.Paused) { Debug.WriteLine("IM here 1"); } if (_shouldStop) { return; } Debug.WriteLine("IM here 2"); _shouldStop = false; waveOut.Stop(); waveOut.Dispose(); SongComplete?.Invoke(); } } } catch (Exception) { Debug.WriteLine("Error happend, moving to next song"); SongComplete?.Invoke(); } }
public void Play() { _WaveOut = new WaveOut(); _WaveOut.Init(this); _WaveOut.Play(); }
public Naudio() { waveIn = new WaveIn(); waveOut = new WaveOut(); fileName = AppDomain.CurrentDomain.BaseDirectory + @"\Temp.wav"; }
/// <summary> /// Default constructor. /// </summary> /// <param name="device">Audio output device.</param> /// <param name="format">Audio output format.</param> /// <exception cref="ArgumentNullException">Is raised when <b>device</b> or <b>format</b> is null reference.</exception> public AudioOut(AudioOutDevice device,AudioFormat format) { if(device == null){ throw new ArgumentNullException("device"); } if(format == null){ throw new ArgumentNullException("format"); } m_pDevice = device; m_pAudioFormat = format; m_pWaveOut = new WaveOut(device,format.SamplesPerSecond,format.BitsPerSample,format.Channels); }
private void InitAudio() { _waveOut = new WaveOut(_buffer, _codec.DecodedFormat, _codec.DecodedBufferSize); _waveOut.Start(); }
public SoundSettings() { InitializeComponent(); Split = SplitAheadGaining = SplitAheadLosing = SplitBehindGaining = SplitBehindLosing = BestSegment = UndoSplit = SkipSplit = PersonalBest = NotAPersonalBest = Reset = Pause = Resume = StartTimer = ""; OutputDevice = 0; GeneralVolume = SplitVolume = SplitAheadGainingVolume = SplitAheadLosingVolume = SplitBehindGainingVolume = SplitBehindLosingVolume = BestSegmentVolume = UndoSplitVolume = SkipSplitVolume = PersonalBestVolume = NotAPersonalBestVolume = ResetVolume = PauseVolume = ResumeVolume = StartTimerVolume = 100; for (int i = 0; i < WaveOut.DeviceCount; ++i) { cbOutputDevice.Items.Add(WaveOut.GetCapabilities(i)); } txtSplitPath.DataBindings.Add("Text", this, "Split"); txtSplitAheadGaining.DataBindings.Add("Text", this, "SplitAheadGaining"); txtSplitAheadLosing.DataBindings.Add("Text", this, "SplitAheadLosing"); txtSplitBehindGaining.DataBindings.Add("Text", this, "SplitBehindGaining"); txtSplitBehindLosing.DataBindings.Add("Text", this, "SplitBehindLosing"); txtBestSegment.DataBindings.Add("Text", this, "BestSegment"); txtUndo.DataBindings.Add("Text", this, "UndoSplit"); txtSkip.DataBindings.Add("Text", this, "SkipSplit"); txtPersonalBest.DataBindings.Add("Text", this, "PersonalBest"); txtNotAPersonalBest.DataBindings.Add("Text", this, "NotAPersonalBest"); txtReset.DataBindings.Add("Text", this, "Reset"); txtPause.DataBindings.Add("Text", this, "Pause"); txtResume.DataBindings.Add("Text", this, "Resume"); txtStartTimer.DataBindings.Add("Text", this, "StartTimer"); cbOutputDevice.DataBindings.Add("SelectedIndex", this, "OutputDevice"); tbGeneralVolume.DataBindings.Add("Value", this, "GeneralVolume"); tbSplitVolume.DataBindings.Add("Value", this, "SplitVolume"); tbSplitAheadGainingVolume.DataBindings.Add("Value", this, "SplitAheadGainingVolume"); tbSplitAheadLosingVolume.DataBindings.Add("Value", this, "SplitAheadLosingVolume"); tbSplitBehindGainingVolume.DataBindings.Add("Value", this, "SplitBehindGainingVolume"); tbSplitBehindLosingVolume.DataBindings.Add("Value", this, "SplitBehindLosingVolume"); tbBestSegmentVolume.DataBindings.Add("Value", this, "BestSegmentVolume"); tbUndoVolume.DataBindings.Add("Value", this, "UndoSplitVolume"); tbSkipVolume.DataBindings.Add("Value", this, "SkipSplitVolume"); tbPersonalBestVolume.DataBindings.Add("Value", this, "PersonalBestVolume"); tbNotAPersonalBestVolume.DataBindings.Add("Value", this, "NotAPersonalBestVolume"); tbResetVolume.DataBindings.Add("Value", this, "ResetVolume"); tbPauseVolume.DataBindings.Add("Value", this, "PauseVolume"); tbResumeVolume.DataBindings.Add("Value", this, "ResumeVolume"); tbStartTimerVolume.DataBindings.Add("Value", this, "StartTimerVolume"); }
public static void Start(Setting setting) { NAudioWrap.setting = setting; if (waveOut != null) { waveOut.Dispose(); } waveOut = null; if (wasapiOut != null) { wasapiOut.Dispose(); } wasapiOut = null; if (dsOut != null) { dsOut.Dispose(); } dsOut = null; if (asioOut != null) { asioOut.Dispose(); } asioOut = null; if (nullOut != null) { nullOut.Dispose(); } nullOut = null; try { switch (setting.outputDevice.DeviceType) { case 0: waveOut = new WaveOutEvent(); waveOut.DeviceNumber = 0; waveOut.DesiredLatency = setting.outputDevice.Latency; for (int i = 0; i < WaveOut.DeviceCount; i++) { if (setting.outputDevice.WaveOutDeviceName == WaveOut.GetCapabilities(i).ProductName) { waveOut.DeviceNumber = i; break; } } waveOut.PlaybackStopped += DeviceOut_PlaybackStopped; waveOut.Init(waveProvider); waveOut.Play(); break; case 1: System.Guid g = System.Guid.Empty; foreach (DirectSoundDeviceInfo d in DirectSoundOut.Devices) { if (setting.outputDevice.DirectSoundDeviceName == d.Description) { g = d.Guid; break; } } if (g == System.Guid.Empty) { dsOut = new DirectSoundOut(setting.outputDevice.Latency); } else { dsOut = new DirectSoundOut(g, setting.outputDevice.Latency); } dsOut.PlaybackStopped += DeviceOut_PlaybackStopped; dsOut.Init(waveProvider); dsOut.Play(); break; case 2: MMDevice dev = null; var enumerator = new MMDeviceEnumerator(); var endPoints = enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active); foreach (var endPoint in endPoints) { if (setting.outputDevice.WasapiDeviceName == string.Format("{0} ({1})", endPoint.FriendlyName, endPoint.DeviceFriendlyName)) { dev = endPoint; break; } } if (dev == null) { wasapiOut = new WasapiOut(setting.outputDevice.WasapiShareMode ? AudioClientShareMode.Shared : AudioClientShareMode.Exclusive, setting.outputDevice.Latency); } else { wasapiOut = new WasapiOut(dev, setting.outputDevice.WasapiShareMode ? AudioClientShareMode.Shared : AudioClientShareMode.Exclusive, false, setting.outputDevice.Latency); } wasapiOut.PlaybackStopped += DeviceOut_PlaybackStopped; wasapiOut.Init(waveProvider); wasapiOut.Play(); break; case 3: if (AsioOut.isSupported()) { int i = 0; foreach (string s in AsioOut.GetDriverNames()) { if (setting.outputDevice.AsioDeviceName == s) { break; } i++; } int retry = 1; do { try { asioOut = new AsioOut(i); } catch { asioOut = null; Thread.Sleep(1000); retry--; } } while (asioOut == null && retry > 0); asioOut.PlaybackStopped += DeviceOut_PlaybackStopped; asioOut.Init(waveProvider); asioOut.Play(); } break; case 5: nullOut = new NullOut(true); nullOut.PlaybackStopped += DeviceOut_PlaybackStopped; nullOut.Init(waveProvider); nullOut.Play(); break; } } catch (Exception ex) { log.ForcedWrite(ex); waveOut = new WaveOutEvent(); waveOut.PlaybackStopped += DeviceOut_PlaybackStopped; waveOut.Init(waveProvider); waveOut.DeviceNumber = 0; waveOut.Play(); } }
public void Dispose() { WaveOut?.Stop(); WaveOut?.Dispose(); WaveStream?.Dispose(); }
public void OpenFile(string path) { Stop(); if (ActiveStream != null) { SelectionBegin = TimeSpan.Zero; SelectionEnd = TimeSpan.Zero; ChannelPosition = 0; } StopAndCloseStream(); if (System.IO.File.Exists(path)) { try { waveOutDevice = new WaveOut() { DesiredLatency = 100 }; var extension = Path.GetExtension(path); if (extension == null) { Debug.WriteLine(string.Format("只能播放有标准后缀名的文件,此文件{0}不标准", path)); return; } //判断是MP3文件还是Wav if (extension.Equals(".mp3", StringComparison.InvariantCultureIgnoreCase)) { ActiveStream = new Mp3FileReader(path); inputStream = new WaveChannel32(ActiveStream); sampleAggregator = new SampleAggregator(fftDataSize); inputStream.Sample += inputStream_Sample; waveOutDevice.Init(inputStream); ChannelLength = inputStream.TotalTime.TotalSeconds; //FileTag = TagLib.File.Create(path); FileTag获取专辑图片,不需要专辑图片 //GenerateWaveformData(path); CanPlay = true; } else if (extension.Equals(".wav", StringComparison.InvariantCultureIgnoreCase)) { ActiveStream = new WaveFileReader(path); inputStream = new WaveChannel32(ActiveStream); sampleAggregator = new SampleAggregator(fftDataSize); inputStream.Sample += inputStream_Sample; waveOutDevice.Init(inputStream); ChannelLength = inputStream.TotalTime.TotalSeconds; //FileTag = TagLib.File.Create(path); FileTag获取专辑图片,不需要专辑图片 //GenerateWaveformData(path); CanPlay = true; } //ActiveStream = new Mp3FileReader(path); //inputStream = new WaveChannel32(ActiveStream); //sampleAggregator = new SampleAggregator(fftDataSize); //inputStream.Sample += inputStream_Sample; //waveOutDevice.Init(inputStream); //ChannelLength = inputStream.TotalTime.TotalSeconds; ////FileTag = TagLib.File.Create(path); FileTag获取专辑图片,不需要专辑图片 //GenerateWaveformData(path); //CanPlay = true; } catch { ActiveStream = null; CanPlay = false; } } }
protected override void PlayAndRecord(string WavFileName, Channel Channel) { ProductName = string.Empty; List <Guid> AudioDeviceList = null; if (Channel == Channel.Left || Channel == Channel.Right) { AudioDeviceList = MachineAudioDeviceList; } else if (Channel == Channel.HeadSet) { AudioDeviceList = ExternalAudioDeviceList; } for (int n = -1; n < WaveOut.DeviceCount; n++) { var caps = WaveOut.GetCapabilities(n); Console.WriteLine("Play device {0}: {1}", n, caps.ProductName); Console.WriteLine(caps.ManufacturerGuid); Trace.WriteLine(caps.ManufacturerGuid); foreach (var v in AudioDeviceList) { if (caps.ManufacturerGuid.Equals(v)) { DeviceNumber = n; ProductName = caps.ProductName; Console.WriteLine("Find"); } } } if (string.IsNullOrEmpty(ProductName) && (Channel == Channel.Left || Channel == Channel.Right)) { throw new Exception("Machine audio device not found"); } else if (string.IsNullOrEmpty(ProductName) && Channel == Channel.HeadSet) { throw new Exception("External audio device not found"); } using (var inputReader = new WaveFileReader(WavFileName)) using (var outputDevice = new WaveOutEvent()) { outputDevice.DeviceNumber = DeviceNumber; Console.WriteLine("Play device: {0}", ProductName); outputDevice.Init(inputReader); outputDevice.PlaybackStopped += (sender, e) => { if (WavSource != null) { WavSource.StopRecording(); } Console.WriteLine("Play Stopped"); }; outputDevice.Play(); if (Channel == Channel.Left) { Record(Channel.Left).Wait(); } else if (Channel == Channel.Right) { Record(Channel.Right).Wait(); } else if (Channel == Channel.HeadSet) { Record(Channel.HeadSet).Wait(); } while (outputDevice.PlaybackState == PlaybackState.Playing) { Thread.Sleep(500); } } }
void listener_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) { string commandName = e.Result.Text; // MessageBox.Show(commandName); if (leaveMeAlone == true) { switch (commandName.ToLower()) { case "you may speak now": case "you may speak": case "speak": case "sound on": case "come back": if (voice == true) { speaker.Speak("Thank you"); } else { printMessage("Thank you"); } label1.Text = "I'm listening"; leaveMeAlone = false; this.Show(); break; } } if (leaveMeAlone == false) { switch (commandName.ToLower()) { case "close": case "leave me alone": case "go away": case "f**k off": case "exit": if (voice == true) { speaker.Speak("Talk to you later"); } else { printMessage("Talk to you later"); } this.Hide(); leaveMeAlone = true; label1.Text = "I am not listening"; break; case "hello": if (voice == true) { speaker.Speak("Hello. How are you doing?"); } else { printMessage("Hello. How are you doing?"); } label1.Text = "☺"; label1.Text = "Hello"; break; case "yes": if (voice == true) { speaker.Speak("What can I do for you?"); } else { printMessage("What can I do for you?"); } label1.Text = "?"; break; case "i'm fine": case "i'm good": case "good": case "fine": label1.Text = ":D"; if (voice == true) { speaker.Speak("I'm glad to hear that"); } else { printMessage("I'm glad to hear that"); } break; case "thank you": label1.Text = ":)"; if (voice == true) { speaker.Speak("You're welcome"); } else { printMessage("You're welcome"); } label1.Text = "You are welcome"; break; case "thanks": label1.Text = ";)"; if (voice == true) { speaker.Speak("No problemo"); } else { printMessage("No problemo"); } break; case "what's the time": case "what time is it": case "can you tell me the time": case "can you tell me what time it is": case "time": speaker.SpeakAsync(DateTime.Now.ToShortTimeString()); break; case "what's the date": case "what day is it": case "what is today's date": case "what is today": case "today": case "date": speaker.SpeakAsync(DateTime.Today.ToString("dddd, MMMM d, yyyy")); break; case "facebook": Process.Start("http://www.facebook.com"); break; case "google": case "search": case "opera": label1.Text = "Google time"; Process.Start("http://www.google.com"); break; case "youtube": Process.Start("http://www.youtube.com"); break; case "my computer": case "computer": case "open my computer": case "files": case "open files": case "open my files": string myComputerPath = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer); Process.Start("explorer", myComputerPath); break; case "what the f**k": if (voice == true) { speaker.Speak("Do you need help, Gabriel?"); } else { printMessage("Do you need help, Gabriel?"); } label1.Text = "WTF?"; break; case "activate voice": case "voice activated": case "switch to voice": speaker.Speak("Voice activated"); label1.Text = "Voice on n***a"; voice = true; break; case "stop speaking": case "stop talking": case "voice deactivated": case "be quiet": case "silence": case "switch to text": voice = false; printMessage("I'm mute"); label1.Text = "Ok I'm muted"; break; case "who are you": case "what is your name": label1.Text = "M"; if (voice == true) { speaker.Speak("My name is M. Your personal assistant"); } else { printMessage("My name is M. Your personal assistant"); } break; case "can you hear me": case "do you hear me": label1.Text = "YES"; if (voice == true) { speaker.Speak("Yes"); } else { printMessage("Yes"); } break; case "play some music": case "play music": case "play my music": case "music": case "play my playlist": Process.Start("www.youtube.com/playlist?list=FLblHYro_OYFvXGrGuzRycCw&playnext_from=PL&index=0&playnext=1"); if (voice == true) { speaker.Speak("Let the music ring ring ring"); } else { printMessage("PAAAARTYYY HOUSE"); } label1.Text = "Music all over the houseeee"; break; case "party": case "friends": //Process.Start("start C:\\Users\\puiu_\\AppData\\Local\\Discord\\Update.exe --processStart Discord.exe"); if (voice == true) { speaker.Speak("Discord party"); } else { printMessage("Discord party"); } label1.Text = "Discord partyy"; break; case "are you listening": //Process.Start("start C:\\Users\\puiu_\\AppData\\Local\\Discord\\Update.exe --processStart Discord.exe"); if (voice == true) { speaker.Speak("Yes"); } else { printMessage("Yes"); } label1.Text = "Ye"; break; case "you can see me now": label1.Text = "Rapanon"; //Process.Start("start C:\\Users\\puiu_\\AppData\\Local\\Discord\\Update.exe --processStart Discord.exe"); if (voice == true) { speaker.Speak("Rapanon"); } else { printMessage("Rapanon"); } IWavePlayer waveOutDevice = new WaveOut(); AudioFileReader audioFileReader = new AudioFileReader("j.mp3"); waveOutDevice.Init(audioFileReader); waveOutDevice.Play(); break; case "joke": case "funny": case "tell me a joke": string result = "Offline"; using (var webClient = new System.Net.WebClient()) { result = webClient.DownloadString("https://api.apithis.net/yomama.php"); } //Process.Start("start C:\\Users\\puiu_\\AppData\\Local\\Discord\\Update.exe --processStart Discord.exe"); if (voice == true) { speaker.Speak(result); } else { printMessage(result); } label1.Text = result; break; default: //handle non-normalized recognition //speaker.SpeakAsync("Can you repeat honey?"); //example, probably should URL encode the value... //Process.Start("http://www.google.com?q=" + commandName); break; } } }
public void LoadSong(string url, bool fromPlaylist = false) { string ext = Path.GetExtension(url); if (loaded) { wave.Dispose(); wvcn.Dispose(); strm.Dispose(); } if (ext.IndexOf("wav") >= 0) { strm = new WaveFileReader(url); } else if (ext.IndexOf("mp3") >= 0) { strm = new Mp3FileReader(url); } else { return; } if (!fromPlaylist && playlistActive) { DialogResult res = MessageBox.Show("Add this song to the current Playlist?", "Update Playlist", MessageBoxButtons.YesNo); if (res == DialogResult.Yes) { currentPlaylist.AddSong(url); DialogResult mes = MessageBox.Show("Save Playlist?", "Save Playlist", MessageBoxButtons.YesNo); if (res == DialogResult.Yes) { currentPlaylist.Save(); } } else { playlistActive = false; } } wave = new WaveOut(); wvcn = new WaveChannel32(strm); wvcn.PadWithZeroes = false; wvcn.Sample += new EventHandler <SampleEventArgs>(SampleEvent); wave.PlaybackStopped += (pbss, e) => { playing = false; nextpos = 0; LoadNext(); }; wave.Volume = volume; wave.Init(wvcn); loaded = true; Paused = false; currentSong = new Song(url, true); if (currentSong.HasArt) { SongColor = ImageProcessor.AverageColor(new Bitmap(currentSong.art)); colorMode = ColorMode.Image; } else { colorMode = ColorMode.Random; } wave.Play(); menuControl.DoSongLoaded(currentSong); using (Graphics g = Graphics.FromImage(SongInformation)) { g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; StringFormat centered = new StringFormat(); centered.Alignment = StringAlignment.Center; centered.LineAlignment = StringAlignment.Center; RectangleF borp = new RectangleF(0, 10, SongInformation.Width, SongInformation.Height); borp.Inflate(-5, -10); g.FillRectangle(Brushes.Lime, borp); int amt = 1 + (currentSong.album != null ? 1 : 0) + (currentSong.albumArtists != "" ? 1 : 0); borp.Height /= amt; g.DrawString(currentSong.title, SongInfoTitleFont, Brushes.Black, borp, centered); borp.Y += borp.Height; if (currentSong.album != null) { g.DrawString(currentSong.album, SongInfoSubFont, Brushes.Black, borp, centered); borp.Y += borp.Height + 5; } if (currentSong.albumArtists != "") { g.DrawString(currentSong.albumArtists, SongInfoSubFont, Brushes.Black, borp, centered); borp.Y += borp.Height + 5; } } }
private void Sock_Opened(string ip, EventArgs e) { WelcomeMessageSnackbar.Visibility = Visibility.Hidden; PopupBox.Visibility = Visibility.Hidden; cam.Visibility = Visibility.Visible; mic.Visibility = Visibility.Visible; bze.Visibility = Visibility.Visible; Flash.Visibility = Visibility.Visible; camera = new WebSocket4Net.WebSocket("ws://" + ip + ":9682"); camera.DataReceived += (ui, ty) => { Gr.Dispatcher.Invoke(new Action(() => { MemoryStream strm = new MemoryStream(ty.Data); var imageSource = new BitmapImage(); imageSource.BeginInit(); imageSource.StreamSource = strm; imageSource.EndInit(); if (cam.Tag.ToString() == "0") { Image rotated90 = new Image(); TransformedBitmap tb = new TransformedBitmap(); tb.BeginInit(); tb.Source = imageSource; // Set image rotation. RotateTransform transform = new RotateTransform(-90); tb.Transform = transform; tb.EndInit(); ImageBrush gh = new ImageBrush(tb); gh.Stretch = Stretch.Fill; Gr.Background = gh; } else { Image rotated90 = new Image(); TransformedBitmap tb = new TransformedBitmap(); tb.BeginInit(); tb.Source = imageSource; // Set image rotation. RotateTransform transform = new RotateTransform(90); tb.Transform = transform; tb.EndInit(); ImageBrush gh = new ImageBrush(tb); gh.Stretch = Stretch.Fill; Gr.Background = gh; } } )); }; camera.Closed += (g, j) => { cam.Dispatcher.Invoke(new Action(() => Sock_Closed(g, j))); }; camera.Open(); audio = new WebSocket4Net.WebSocket("ws://" + ip + ":9676"); var ou = new WaveOut(WaveOut.Devices[0], 8000, 16, 1); audio.DataReceived += (gh, data) => { ou.Play(data.Data, 0, data.Data.Length); }; audio.Closed += (h, d) => { ou.Dispose(); }; audio.Open(); oi = new WaveIn(WaveIn.Devices[0], 8000, 16, 1, 400); speaker = new WebSocket4Net.WebSocket("ws://" + ip + ":9679"); oi.BufferFull += Oi_BufferFull; speaker.Open(); }
private void start1Button_Click(object sender, EventArgs e) { //IPAddress myIP = IPAddress.Parse("0.0.0.0"); //IPAddress[] localIP = Dns.GetHostAddresses("ASUS-PC"); //foreach (IPAddress address in localIP) //{ // if (address.AddressFamily == AddressFamily.InterNetwork) // { // myIP = address; // } //} if (m_IsRunning) { m_IsRunning = false; m_IsSendingTest = false; m_pUdpServer.Dispose(); m_pUdpServer = null; m_pWaveOut.Dispose(); m_pWaveOut = null; if (m_pRecordStream != null) { m_pRecordStream.Dispose(); m_pRecordStream = null; } m_pTimer.Dispose(); m_pTimer = null; m_pInDevices.Enabled = true; m_pOutDevices.Enabled = true; m_pCodec.Enabled = true; start1Button.Text = "Start"; m_pRecord.Enabled = true; m_pRecordFile.Enabled = true; m_pRecordFileBrowse.Enabled = true; m_pRemoteIP.Enabled = false; m_pRemotePort.Enabled = false; startLocalButton.Text = "Start"; startLocalButton.Enabled = false; m_pSendTestSound.Enabled = false; m_pSendTestSound.Text = "Start"; m_pPlayTestSound.Enabled = false; m_pPlayTestSound.Text = "Play"; } else { if (m_pOutDevices.SelectedIndex == -1) { MessageBox.Show(this, "Please select output device !", "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (m_pRecord.Checked && m_pRecordFile.Text == "") { MessageBox.Show(this, "Please specify record file !", "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (m_pRecord.Checked) { m_pRecordStream = File.Create(m_pRecordFile.Text); } m_IsRunning = true; m_Codec = m_pCodec.SelectedIndex; m_pWaveOut = new WaveOut(WaveOut.Devices[m_pOutDevices.SelectedIndex], 8000, 16, 1); ///// m_pUdpServer = new UdpServer(); m_pUdpServer.Bindings = new IPEndPoint[] { new IPEndPoint(IPAddress.Parse(m_pLoacalIP.Text), 11000) }; m_pUdpServer.PacketReceived += new PacketReceivedHandler(m_pUdpServer_PacketReceived); m_pUdpServer.Start(); m_pTimer = new System.Windows.Forms.Timer(); m_pTimer.Interval = 1000; m_pTimer.Tick += new EventHandler(m_pTimer_Tick); m_pTimer.Enabled = true; m_pInDevices.Enabled = false; m_pOutDevices.Enabled = false; m_pCodec.Enabled = false; start1Button.Text = "Stop"; m_pRecord.Enabled = false; m_pRecordFile.Enabled = false; m_pRecordFileBrowse.Enabled = false; m_pRemoteIP.Enabled = true; m_pRemotePort.Enabled = true; startLocalButton.Enabled = true; m_pSendTestSound.Enabled = true; m_pSendTestSound.Text = "Start"; m_pPlayTestSound.Enabled = true; m_pPlayTestSound.Text = "Play"; } }
/// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { if(m_IsDisposed){ return; } m_IsDisposed = true; m_pWaveOut.Dispose(); m_pWaveOut = null; }
public override void StopPlugin() { output.Dispose(); output = null; Logger.Info("Plugin stopped"); }
//got helps from erszcz on stackoverflow static void Main(string[] args) { IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000); // endpoint where server is listening var buffer = new byte[16384 * 4]; client.Connect(ep); client.Send(new byte[] { 1, 2, 3, 4, 5 }, 5); // send data BufferedWaveProvider bufferedWaveProvider = null; WaveOut waveOut = new WaveOut(); IMp3FrameDecompressor decomp = null; int count = 0; // then receive data do { var receivedData = client.Receive(ref ep); Console.WriteLine("receive data from " + ep.ToString()); client.Send(new byte[] { 1, 2, 3, 4, 5 }, 5); Mp3Frame frame; Stream ms = new MemoryStream(); ms.Write(receivedData, 0, receivedData.Length); ms.Position = 0; frame = Mp3Frame.LoadFromStream(ms, true); if (decomp == null) { WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frame.FrameLength, frame.BitRate); decomp = new AcmMp3FrameDecompressor(waveFormat); bufferedWaveProvider = new BufferedWaveProvider(decomp.OutputFormat); bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(20); //var volumeProvider = new VolumeWaveProvider16(bufferedWaveProvider); //volumeProvider.Volume = 1; waveOut.Init(bufferedWaveProvider); // allow us to get well ahead of ourselves //this.bufferedWaveProvider.BufferedDuration = 250; } if (bufferedWaveProvider.BufferedDuration.TotalSeconds > 4) { waveOut.Play(); } int decompressed = decomp.DecompressFrame(frame, buffer, 0); bufferedWaveProvider.AddSamples(buffer, 0, decompressed); count++; } while (bufferedWaveProvider.BufferedDuration.TotalSeconds < 18); //Debug.WriteLine(String.Format("Decompressed a frame {0}", decompressed)); //PlayMp3FromUrl(receivedData); Console.Read(); }
public AudioPipeline AddOutput(WaveOut waveOut) { _waveOutput = waveOut; return(this); }
public static void receivingSong() { waveOut = new WaveOut(); decomp = null; int count = 0; var buffer = new byte[16384 * 4]; do { current = Thread.CurrentThread; if (bufferedWaveProvider != null && bufferedWaveProvider.BufferedDuration.TotalSeconds > 5) { Thread.Sleep(200); if (buffering == false) { break; } } byte[] receivedData = new byte[2000]; if (!receiveData(ref receivedData)) { break; } if (Encoding.ASCII.GetString(receivedData) == "done") { break; } else { client.Send(Encoding.ASCII.GetBytes("more"), 4); // Nhan change value here } Mp3Frame frame; Stream ms = new MemoryStream(); ms.Write(receivedData, 0, receivedData.Length); ms.Position = 0; frame = Mp3Frame.LoadFromStream(ms, true); if (decomp == null) { try { WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frame.FrameLength, frame.BitRate); decomp = new AcmMp3FrameDecompressor(waveFormat); } catch { break; } bufferedWaveProvider = new BufferedWaveProvider(decomp.OutputFormat); bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(20); } if (bufferedWaveProvider.BufferedDuration.TotalSeconds > 5 && waveOut.PlaybackState == PlaybackState.Stopped && buffering == true) { try { waveOut.Init(bufferedWaveProvider); waveOut.Play(); } catch { break; } } try { int decompressed = decomp.DecompressFrame(frame, buffer, 0); bufferedWaveProvider.AddSamples(buffer, 0, decompressed); } catch { break; } count++; } while (buffering); }
/// <summary> /// Default constructor /// </summary> public MainWindow() { InitializeComponent(); this.DataContext = new MusicItemViewModel(this); Player = new WaveOut(); }
public MainViewModel(IDataService dataService) { _dataService = dataService; schedules = new ObservableCollection <Schedule>(); ReadAllCommand = new RelayCommand(GetSchedules); SaveAllCommand = new RelayCommand(SaveAll); AddNewSoundCommand = new RelayCommand(AddNewSound); BrowseFileCommand = new RelayCommand(BrowseFile); CloseSoundCommand = new RelayCommand(CloseSoundFlyout); CloseAlarmCommand = new RelayCommand(CloseAlarmFlyout); PlayCommand = new RelayCommand <Sound>(Play); StopCommand = new RelayCommand(Stop); ApplicationExitRelayCommand = new RelayCommand(OnAppExit); DeleteSoundRelayCommand = new RelayCommand <Sound>(DeleleteSound); RowEditEndingRelayCommand = new RelayCommand(row_editEnding); ShowNewScheduleRelayCommand = new RelayCommand(ShowNewSchedule); RestoreCommand = new RelayCommand(Restore); BackupCommand = new RelayCommand(BackUp); alarmTimer = new Timer { Enabled = false }; Microsoft.Win32.SystemEvents.TimeChanged += TimeHandler; alarmTimer.Tick += alarmTimer_Tick; EverySecondTimer = new Timer(); EverySecondTimer.Tick += EverySecondTimer_Tick; EverySecondTimer.Interval = 1000; MidnighTimer = new Timer(); MidnighTimer.Tick += MidnighTimer_Tick; newDayTimer = new Timer(); waveOut = new WaveOut(); soundStream = new MemoryStream(); waveOut.PlaybackStopped += new EventHandler <StoppedEventArgs>(waveOut_PlaybackStopped); DefaultWeeklySchedule = _dataService.GetDefaultWeeklySchedule(); GetSoundDevices(); ShowSettingsRelayCommand = new RelayCommand(ShowSettings); notifyIcon = new NotifyIcon { Icon = new Icon("Resources\\n_icon.ico") }; notifyIcon.DoubleClick += notifyIcon_DoubleClick; ShowInTaskBar = true; MainWindowState = WindowState.Normal; if (System.IO.File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.Startup) + @"\Alarm Manager.lnk")) { StartOnStartup = true; } Accents = new ObservableCollection <Accent>(ThemeManager.Accents); Themes = new ObservableCollection <AppTheme>(ThemeManager.AppThemes); if (Properties.Settings.Default.IsStartup == true) { MainWindowState = WindowState.Minimized; } if (Properties.Settings.Default.SoundCard < DeviceCollection.Count) { SelectedDevice = Properties.Settings.Default.SoundCard; } else { Properties.Settings.Default.SoundCard = 0; Properties.Settings.Default.Save(); } CurrentAccent = Accents.First(z => z.Name == Properties.Settings.Default.Acent); CurrentTheme = Themes.First(z => z.Name == Properties.Settings.Default.Theme); ThemeManager.ChangeAppStyle(Application.Current, CurrentAccent, currentTheme); var desktopWorkingArea = System.Windows.SystemParameters.WorkArea; AsideLeft = Convert.ToInt32(desktopWorkingArea.Right - 280); AsideTop = 0; IsSpinningCircleEnable = true; StartScheduler(); }
// Sets up and plays music file that was read in private void playBack() { playback = new WaveOut(); playback.Init(waveReader); playback.Play(); }
private void btnPlay_Click(object sender, RoutedEventArgs e) { if (wavePlayer != null) { wavePlayer.Dispose(); } debugStreamController = new DebugStreamController(); MixerStream mixer = new MixerStream(2, 44100); foreach (AudioTrack audioTrack in trackListBox.Items) { WaveFileReader reader = new WaveFileReader(audioTrack.FileInfo.FullName); IeeeStream channel = new IeeeStream(new DebugStream(new NAudioSourceStream(reader), debugStreamController)); //ResamplingStream res = new ResamplingStream(new DebugStream(channel, debugStreamController), ResamplingQuality.SincBest, 22050); TimeWarpStream warp = new TimeWarpStream(new DebugStream(channel, debugStreamController)); //warp.Mappings.Add(new TimeWarp { From = new TimeSpan(audioTrack.Length.Ticks / 10 * 4), To = new TimeSpan(audioTrack.Length.Ticks / 9) }); //warp.Mappings.Add(new TimeWarp { From = new TimeSpan(audioTrack.Length.Ticks / 10 * 5), To = new TimeSpan(audioTrack.Length.Ticks / 9 * 2) }); //warp.Mappings.Add(new TimeWarp { From = new TimeSpan(audioTrack.Length.Ticks / 10 * 10), To = new TimeSpan(audioTrack.Length.Ticks / 9 * 3) }); // necessary to control each track individually VolumeControlStream volumeControl = new VolumeControlStream(new DebugStream(warp, debugStreamController)) { Mute = audioTrack.Mute, Volume = audioTrack.Volume }; // when the AudioTrack.Mute property changes, just set it accordingly on the audio stream audioTrack.MuteChanged += new EventHandler <ValueEventArgs <bool> >( delegate(object vsender, ValueEventArgs <bool> ve) { volumeControl.Mute = ve.Value; }); // when the AudioTrack.Solo property changes, we have to react in different ways: audioTrack.SoloChanged += new EventHandler <ValueEventArgs <bool> >( delegate(object vsender, ValueEventArgs <bool> ve) { AudioTrack senderTrack = (AudioTrack)vsender; bool isOtherTrackSoloed = false; foreach (AudioTrack vaudioTrack in trackListBox.Items) { if (vaudioTrack != senderTrack && vaudioTrack.Solo) { isOtherTrackSoloed = true; break; } } /* if there's at least one other track that is soloed, we set the mute property of * the current track to the opposite of the solo property: * - if the track is soloed, we unmute it * - if the track is unsoloed, we mute it */ if (isOtherTrackSoloed) { senderTrack.Mute = !ve.Value; } /* if this is the only soloed track, we mute all other tracks * if this track just got unsoloed, we unmute all other tracks */ else { foreach (AudioTrack vaudioTrack in trackListBox.Items) { if (vaudioTrack != senderTrack && !vaudioTrack.Solo) { vaudioTrack.Mute = ve.Value; } } } }); // when the AudioTrack.Volume property changes, just set it accordingly on the audio stream audioTrack.VolumeChanged += new EventHandler <ValueEventArgs <float> >( delegate(object vsender, ValueEventArgs <float> ve) { volumeControl.Volume = ve.Value; }); mixer.Add(new DebugStream(volumeControl)); } VolumeControlStream volumeControlStream = new VolumeControlStream(new DebugStream(mixer, debugStreamController)) { Volume = (float)volumeSlider.Value }; VolumeMeteringStream volumeMeteringStream = new VolumeMeteringStream(new DebugStream(volumeControlStream, debugStreamController), 5000); volumeMeteringStream.StreamVolume += new EventHandler <StreamVolumeEventArgs>(meteringStream_StreamVolume); VolumeClipStream volumeClipStream = new VolumeClipStream(new DebugStream(volumeMeteringStream, debugStreamController)); playbackStream = volumeClipStream; wavePlayer = new WaveOut(); wavePlayer.DesiredLatency = 250; wavePlayer.Init(new NAudioSinkStream(new DebugStream(playbackStream, debugStreamController))); // master volume setting volumeSlider.ValueChanged += new RoutedPropertyChangedEventHandler <double>( delegate(object vsender, RoutedPropertyChangedEventArgs <double> ve) { volumeControlStream.Volume = (float)ve.NewValue; }); lblTotalPlaybackTime.Content = TimeUtil.BytesToTimeSpan(playbackStream.Length, playbackStream.Properties); playbackSeeker.Maximum = TimeUtil.BytesToTimeSpan(playbackStream.Length, playbackStream.Properties).TotalSeconds; wavePlayer.Play(); }