Esempio n. 1
0
 private ISampleProvider CreateInputStream(string fileName)
 {
     if (fileName.EndsWith(".wav"))
     {
         fileStream = OpenWavStream(fileName);
     }
     else if (fileName.EndsWith(".mp3"))
     {
         fileStream = new Mp3FileReader(fileName);
     }
     else
     {
         throw new InvalidOperationException("Unsupported extension");
     }
     var inputStream = new SampleChannel(fileStream);
     var sampleStream = new NotifyingSampleProvider(inputStream);
     sampleStream.Sample += (s, e) => aggregator.Add(e.Left);
     return sampleStream;
 }
        private void _play()
        {
            /* Audio chain */

            // Sampling
            _wavesampler = new WaveToSampleProvider(new Wave16ToFloatProvider(_wavebuffer));

            // Fading component
            _fade = new FadeInOutSampleProvider(_wavesampler);
            _fade.BeginFadeIn(1500);

            // Notifying component
            var _notify = new NotifyingSampleProvider(_fade);
            _notify.Sample += new EventHandler<SampleEventArgs>(_notify_Sample);

            // Gain adjustment component
            _volume = new VolumeSampleProvider(_notify);
            _volume.Volume = this.Volume;

            // Output
            Output.Init(new SampleToWaveProvider16(_volume));

            /* Playback loop */
            do
            {
                if (_cancel_play.IsCancellationRequested)
                {
                    Console.WriteLine("[Playback thread] Cancellation requested.");

                    // Fade out and stop
                    Console.WriteLine("[Playback thread] Fading out and stopping...");
                    _fade.BeginFadeOut(500);
                    Thread.Sleep(500);
                    Output.Stop();
                    Console.WriteLine("[Playback thread] Output stopped.");
                    this.Status = StreamStatus.Stopped;
                    Console.WriteLine("[Playback thread] Acknowledged as status.");

                    //_cancel_play_token.ThrowIfCancellationRequested();
                    //Console.WriteLine("[Playback thread] WARNING: Cancellation token is not cleanly set!");
                    return;
                }

                if (Output.PlaybackState != PlaybackState.Playing && _wavebuffer.BufferedDuration.TotalMilliseconds > 2750)
                {
                    // Buffer is filled enough
                    Console.WriteLine("[Playback thread] Buffer is okay now, start playback!");
                    this.Status = StreamStatus.Playing;
                    Output.Play();
                }
                else if (Output.PlaybackState == PlaybackState.Playing && _wavebuffer.BufferedDuration.TotalMilliseconds < 2250)
                {
                    // Buffer is underrunning
                    Console.WriteLine("[Playback thread] Buffer is underrunning, pausing playback...");
                    this.Status = StreamStatus.Buffering;
                    Output.Pause();
                }

                if (_bufferThread.Exception != null)
                {
                    Console.WriteLine("[Playback thread] Buffering thread is faulted, aborting playback");
                    throw new Exception("Buffering thread faulted, aborting playback");
                }

                Thread.Sleep(100);
            }
            while (true);
        }
Esempio n. 3
0
 /// <summary>
 /// Generates the input stream based on what kind of file it is.
 /// </summary>
 /// <param name="fileName">Name of the file about to be played.</param>
 private void CreateInputStream(string fileName)
 {
     SampleChannel inputStream;
     if (fileName.EndsWith(".wav"))
     {
         readerStream = new WaveFileReader(fileName);
         if (readerStream.WaveFormat.Encoding != WaveFormatEncoding.Pcm)
         {
             readerStream = WaveFormatConversionStream.CreatePcmStream(readerStream);
             readerStream = new BlockAlignReductionStream(readerStream);
         }
         if (readerStream.WaveFormat.BitsPerSample != 16)
         {
             var format = new WaveFormat(readerStream.WaveFormat.SampleRate,
                  16, readerStream.WaveFormat.Channels);
             readerStream = new WaveFormatConversionStream(format, readerStream);
         }
         inputStream = new SampleChannel(readerStream);
     }
     else if (fileName.EndsWith(".mp3"))
     {
         readerStream = new Mp3FileReader(fileName);
         inputStream = new SampleChannel(readerStream);
     }
     else
     {
         throw new InvalidOperationException("Unsupported extension");
     }
     sampleProvider = new NotifyingSampleProvider(inputStream);
     sampleProvider.Sample += (s, e) => aggregator.Add(e.Left, e.Right);
 }
Esempio n. 4
0
        private void Start(Audio.Codecs.INetworkChatCodec codec)
        {
            ShouldTryRestartOutput = false;

            Stop();

            waveOut = GetWavePlayer();

            waveProvider = new BufferedWaveProvider(codec.RecordFormat);

            sampleChannel = new SampleChannel(waveProvider, false);
            sampleStream = new NotifyingSampleProvider(sampleChannel);
            sampleStream.Sample += (s, e) => aggregator.Add(e.Left);
            waveOut.Init(sampleStream);
            waveOut.Play();

            if (LevelManager == null)
                LevelManager = new AudioLevelManagerDisconnected();

            OutputFormat = codec.RecordFormat.ToString();
        }
Esempio n. 5
0
 internal void Stop()
 {
     if (waveOut != null)
     {
         waveOut.Stop();
         try
         {
             waveOut.Dispose();
         }
         catch { }
         waveOut = null;
     }
     waveProvider = null;
     sampleChannel = null;
     sampleStream = null;
 }
Esempio n. 6
0
		private void WaveControl_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			if (e.Button == MouseButtons.Left) {
				stopPlayer();
				if (m_Dragging) {
					if (cursorEvent != null) {
						// Have finished dragging - fire event
						cursorEvent.Cursor.FireCursorMoveFinished(cursorEvent);
						cursorEvent = null;
					}
					m_Dragging = false;
				} else if(!m_PlayerJustStopped) {
					if (m_Wavefile != null) {
						if (m_DragStart == null || Math.Abs(e.X - m_DragStart.X) > 5 || Math.Abs(e.Y - m_DragStart.Y) > 5)
							return;		// Ignore everything except click
						float start = m_StartSeconds;					// Where to start playing
						float end = m_StartSeconds + m_LengthSeconds;	// and end
						float pixelsPerSecond = Width / m_LengthSeconds;
						if (m_Cursors != null) {
							// Play only between cursors
							for (int i = 0; i < m_Cursors.Length; i++) {
								PositionCursor c = m_Cursors[i];
								if (!c.Active)
									continue;
								float x = (c.Position - m_StartSeconds) * pixelsPerSecond;
								if (x <= e.X)
									start = Math.Max(start, c.Position);
								else
									end = Math.Min(end, c.Position);
							}
						}
						// If click not near start, start from click position
						float sx = (start - m_StartSeconds) * pixelsPerSecond;
						if (e.X - sx > 20)
							start = m_StartSeconds + e.X / pixelsPerSecond;
						m_Wavefile.Position = WaveFormat.SecondsToBytes(start);
						NotifyingSampleProvider p = new NotifyingSampleProvider(new OffsetSampleProvider(m_Wavefile) {
							Take = new TimeSpan((long)(10000000 * (end - start)))
						});
						p.Sample += SampleCounter;		// To keep track of samples played, for play position cursor
						m_SampleCount = (int)(start * WaveFormat.SampleRate);	// Play position, in samples
						m_Timer.Interval = (int)(1000 / pixelsPerSecond);		// Should fire about every pixel
						m_Timer.Start();
						m_CurrentPlayer = m_Player = new NAudio.Wave.DirectSoundOut();
						m_Player.PlaybackStopped += PlaybackStopped;
						if(Control.ModifierKeys == Keys.Control)	// Play filtered sound
							m_Player.Init(new FilteredSampleProvider(p, Properties.Settings.Default.SilenceFilterCentre, Properties.Settings.Default.SilenceFilterQ));
						else {
								// Play wave file
						}
							m_Player.Init(p);
						m_Player.Play();
						Refresh();
					}
				}
			}
			m_PlayerJustStopped = false;
		}
 private static ISampleProvider CreateSampleStream(WaveStream fileStream)
 {
     var inputStream = new SampleChannel(fileStream);
     var sampleStream = new NotifyingSampleProvider(inputStream);
     return sampleStream;
 }
Esempio n. 8
0
        public MainWindow(string[] args)
        {
            InitializeComponent();

            sliderMinFreq.Maximum = sliderMaxFreq.Value = sliderMaxFreq.Maximum = SampleRate;

            if (args.Length >= 1)
            {
                int.TryParse(args[0], out _inputDeviceNo);
            }
            if (args.Length >= 2)
            {
                int.TryParse(args[1], out _outputDeviceNo);
            }

            /* Input waveform */
            IWaveProvider inputWaveform;

            if (args.Length >= 3) /* TODO: button for this */
            {
                _waveInFileStream = new WaveFileReader(args[2]);
                if (_waveInFileStream.WaveFormat.Encoding != WaveFormatEncoding.Pcm)
                {
                    _waveInFileStream = WaveFormatConversionStream.CreatePcmStream(_waveInFileStream);
                    _waveInFileStream = new BlockAlignReductionStream(_waveInFileStream);
                }

                if (_waveInFileStream.WaveFormat.BitsPerSample != 16)
                {
                    var format = new WaveFormat(_waveInFileStream.WaveFormat.SampleRate, 16, _waveInFileStream.WaveFormat.Channels);
                    _waveInFileStream = new WaveFormatConversionStream(format, _waveInFileStream);
                }
                inputWaveform = new LoopingStream(new WaveChannel32(_waveInFileStream));
            }
            else
            {
                _waveInDevice = new WaveIn
                {
                    DeviceNumber = _inputDeviceNo,
                    WaveFormat = new WaveFormat(SampleRate, 16, 1)
                };
                _waveInDevice.StartRecording();

                inputWaveform = new WaveInProvider(_waveInDevice);
            }

            /* Input processing pipeline */
            ISampleProvider sampleChannel = new SampleChannel(inputWaveform); //TODO: when we're not using recorder any more, this stay as a wave provider, I think
            _bandPassProvider = new BandPass2(sampleChannel);
            NotifyingSampleProvider sampleStream = new NotifyingSampleProvider(_bandPassProvider);
            _polygonSpectrumControl.bp2 = _bandPassProvider;

            /* Output */
            _waveOutDevice = new WaveOut
            {
                DeviceNumber = _outputDeviceNo,
                Volume = 1
            };
            _waveOutDevice.Init(new SampleToWaveProvider(sampleStream));
            _waveOutDevice.Play();

            /* UI Events */
            sliderMinFreq.ValueChanged += SliderMinFreqValueChanged;
            sliderMaxFreq.ValueChanged += SliderMaxFreqValueChanged;
            textBoxPistonDiameter.TextChanged += textBoxPistonDiameter_TextChanged;
            textBoxEpsilon.TextChanged += textBoxEpsilon_TextChanged;

            UpdateShit();
        }