Exemplo n.º 1
0
        public AudioData Mix(AudioData front, AudioData mix)     // This mixes mix with Front.  Format changed to MIX.
        {
            if (front == null || mix == null)
            {
                return(null);
            }

            IWaveSource frontws = (IWaveSource)front.data;
            IWaveSource mixws   = (IWaveSource)mix.data;

            if (frontws.WaveFormat.Channels < mixws.WaveFormat.Channels)      // need to adapt to previous format
            {
                frontws = frontws.ToStereo();
            }
            else if (frontws.WaveFormat.Channels > mixws.WaveFormat.Channels)
            {
                frontws = frontws.ToMono();
            }

            if (mixws.WaveFormat.SampleRate != frontws.WaveFormat.SampleRate || mixws.WaveFormat.BitsPerSample != frontws.WaveFormat.BitsPerSample)
            {
                frontws = ChangeSampleDepth(frontws, mixws.WaveFormat.SampleRate, mixws.WaveFormat.BitsPerSample);
            }

            IWaveSource s = new MixWaveSource(frontws, mixws);

            System.Diagnostics.Debug.Assert(s != null);
            return(new AudioData(s));
        }
Exemplo n.º 2
0
        public AudioData Append(AudioData front, AudioData end)      // this adds END to Front.   Format is changed to END
        {
            if (front == null || end == null)
            {
                return(null);
            }

            IWaveSource frontws = (IWaveSource)front.data;
            IWaveSource mixws   = (IWaveSource)end.data;

            if (frontws.WaveFormat.Channels < mixws.WaveFormat.Channels)      // need to adapt to previous format
            {
                frontws = frontws.ToStereo();
            }
            else if (frontws.WaveFormat.Channels > mixws.WaveFormat.Channels)
            {
                frontws = frontws.ToMono();
            }

            if (mixws.WaveFormat.SampleRate != frontws.WaveFormat.SampleRate || mixws.WaveFormat.BitsPerSample != frontws.WaveFormat.BitsPerSample)
            {
                frontws = ChangeSampleDepth(frontws, mixws.WaveFormat.SampleRate, mixws.WaveFormat.BitsPerSample);
            }

            IWaveSource s = new AppendWaveSource(frontws, mixws);

            System.Diagnostics.Debug.Assert(s != null);
            return(new AudioData(s));
        }
Exemplo n.º 3
0
        private static Task Player(IWaveSource decoder, WasapiOut device)
        {
            if (device.PlaybackState != PlaybackState.Stopped)
            {
                device.Stop();
            }

            device.Initialize(decoder.ToMono()); //Mono > Stereo in micspams
            device.Play();
            return(Task.FromResult <object>(null));
        }
Exemplo n.º 4
0
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var openFileDialog = new OpenFileDialog()
            {
                Filter = CodecFactory.SupportedFilesFilterEn,
                Title  = "Select a file..."
            };

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                Stop();

                const FftSize fftSize = FftSize.Fft4096;

                IWaveSource source = CodecFactory.Instance.GetCodec(openFileDialog.FileName);

                var spectrumProvider = new BasicSpectrumProvider(source.WaveFormat.Channels,
                                                                 source.WaveFormat.SampleRate, fftSize);
                _lineSpectrum = new LineSpectrum(fftSize)
                {
                    SpectrumProvider = spectrumProvider,
                    UseAverage       = true,
                    BarCount         = 50,
                    BarSpacing       = 2,
                    IsXLogScale      = true,
                    ScalingStrategy  = ScalingStrategy.Sqrt
                };
                _voicePrint3DSpectrum = new VoicePrint3DSpectrum(fftSize)
                {
                    SpectrumProvider = spectrumProvider,
                    UseAverage       = true,
                    PointCount       = 200,
                    IsXLogScale      = true,
                    ScalingStrategy  = ScalingStrategy.Sqrt
                };

                var notificationSource = new SingleBlockNotificationStream(source.ToSampleSource());
                notificationSource.SingleBlockRead += (s, a) => spectrumProvider.Add(a.Left, a.Right);

                _source = notificationSource.ToWaveSource(16);

                _soundOut = new WasapiOut();
                _soundOut.Initialize(_source.ToMono());
                _soundOut.Play();

                timer1.Start();

                propertyGridTop.SelectedObject    = _lineSpectrum;
                propertyGridBottom.SelectedObject = _voicePrint3DSpectrum;
            }
        }
Exemplo n.º 5
0
        private static Task Player(IWaveSource decoder, WasapiOut device)
        {
            //todo: this shit can f**k up!
            while (device.PlaybackState != PlaybackState.Stopped)
            {
                device.Stop();
            }

            Logger.Write(Logger.Status.Info, "Current device.PlaybackState is stopped: " + ((device.PlaybackState == PlaybackState.Stopped) ? "True" : device.PlaybackState.ToString()));
            try
            {
                device.Initialize(decoder.ToMono()); //Mono > Stereo in micspams
            }
            catch (InvalidOperationException e)
            {
                device = new WasapiOut();
                device.Initialize(decoder.ToMono());
                Logger.Write(Logger.Status.Error, "device.PlaybackState was not equal to PlaybackState.Stopped. Error: " + e.ToString());
            }

            device.Play();
            return(Task.FromResult <object>(null));
        }
Exemplo n.º 6
0
        public static void RecordTo(string fileName, TimeSpan time, WaveFormat format)
        {
            CaptureMode captureMode = CaptureMode.Capture;
            DataFlow    dataFlow    = captureMode == CaptureMode.Capture ? DataFlow.Capture : DataFlow.Render;

            var devices = MMDeviceEnumerator.EnumerateDevices(dataFlow, DeviceState.Active);
            var device  = devices.FirstOrDefault();

            using (WasapiCapture soundIn = captureMode == CaptureMode.Capture
                ? new WasapiCapture()
                : new WasapiLoopbackCapture())
            {
                soundIn.Device = device;
                soundIn.Initialize();
                SoundInSource soundInSource = new SoundInSource(soundIn)
                {
                    FillWithZeros = false
                };
                IWaveSource convertedSource = soundInSource
                                              .ChangeSampleRate(format.SampleRate) // sample rate
                                              .ToSampleSource()
                                              .ToWaveSource(format.BitsPerSample); //bits per sample
                using (convertedSource = format.Channels == 1 ? convertedSource.ToMono() : convertedSource.ToStereo())
                {
                    using (WaveWriter waveWriter = new WaveWriter(fileName, convertedSource.WaveFormat))
                    {
                        soundInSource.DataAvailable += (s, e) =>
                        {
                            byte[] buffer = new byte[convertedSource.WaveFormat.BytesPerSecond / 2];
                            int    read;
                            while ((read = convertedSource.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                waveWriter.Write(buffer, 0, read);
                            }
                        };

                        soundIn.Start();

                        Console.WriteLine("Started recording");
                        Thread.Sleep(time);

                        soundIn.Stop();
                        Console.WriteLine("Finished recording");
                    }
                }
            }
        }
Exemplo n.º 7
0
        public void SetFile(string filePath)
        {
            _isPlayingOnBackground = false;

            if (this.FindNextEndPoints().Count > 0)
            {
                SetCircuitDown();
            }

            _audioSource = CodecFactory.Instance.GetCodec(filePath);
            if (_audioSource.WaveFormat.Channels == 2)
            {
                _audioSource = _audioSource.ToMono();
            }
            _audioSource.Position = _audioSource.Length;

            if (this.FindNextEndPoints().Count > 0)
            {
                SetCircuitUp();
            }
        }
Exemplo n.º 8
0
        public SoundInSourceWrapper(SoundInSource soundIn, BroadcastSettings settings)
        {
            Settings = settings;

            _soundIn = soundIn;

            _convertedSource =
                soundIn.ChangeSampleRate(Settings.SampleRate).ToSampleSource().ToWaveSource(Settings.BitDepth);

            if (settings.Channel == AudioChannel.Mono)
            {
                _convertedSource = _convertedSource.ToMono();
            }
            else
            {
                _convertedSource = _convertedSource.ToStereo();
            }

            _audioChunks = new ConcurrentQueue <byte[]>();

            _soundIn.DataAvailable += SoundInDataAvailable;
        }
Exemplo n.º 9
0
        private void InitializeAudioCapture(MMDevice selectedDevice)
        {
            if (selectedDevice != null)
            {
                mAudioCapture = selectedDevice.DataFlow == DataFlow.Capture ?
                                new WasapiCapture() : new WasapiLoopbackCapture();
                mAudioCapture.Device = selectedDevice;
                mAudioCapture.Initialize();
                mAudioCapture.DataAvailable += Capture_DataAvailable;
                mSoundInSource = new SoundInSource(mAudioCapture)
                {
                    FillWithZeros = false
                };
                //create a source, that converts the data provided by the
                //soundInSource to required format
                mConvertedSource = mSoundInSource
                                   .ChangeSampleRate(SampleRate) // sample rate
                                   .ToSampleSource()
                                   .ToWaveSource(16);            //bits per sample

                mConvertedSource = mConvertedSource.ToMono();
            }
        }
Exemplo n.º 10
0
        public void Start()
        {
            if (_device == null || (_soundIn != null && _soundIn.RecordingState == RecordingState.Recording))
            {
                return;
            }
            //create a new soundIn instance
            _soundIn = _captureMode == CaptureMode.Capture ? new WasapiCapture() : new WasapiLoopbackCapture();
            //optional: set some properties
            _soundIn.Device = _device;

            //initialize the soundIn instance
            _soundIn.Initialize();

            //create a SoundSource around the the soundIn instance
            //this SoundSource will provide data, captured by the soundIn instance
            SoundInSource soundInSource = new SoundInSource(_soundIn)
            {
                FillWithZeros = false
            };

            //create a source, that converts the data provided by the
            //soundInSource to any other format
            //in this case the "Fluent"-extension methods are being used
            _convertedSource = soundInSource
                               .ChangeSampleRate(sampleRate) // sample rate
                               .ToSampleSource()
                               .ToWaveSource(bitsPerSample); //bits per sample

            //channels...
            _convertedSource = channels == 1 ? _convertedSource.ToMono() : _convertedSource.ToStereo();
            _waveWriter      = new WaveWriter("out.wav", _convertedSource.WaveFormat);

            soundInSource.DataAvailable += OnDatAvailable;
            _soundIn.Start();
        }
        private void StartCapture(string fileName)
        {
            //Capture Mode
            CaptureMode = (CaptureMode)1;
            DataFlow dataFlow = CaptureMode == CaptureMode.Capture ? DataFlow.Capture : DataFlow.Render;
            //

            //Getting the audio devices from
            var devices = MMDeviceEnumerator.EnumerateDevices(dataFlow, DeviceState.Active);

            if (!devices.Any())
            {
                MessageBox.Show("No devices found.");
                return;
            }

            int selectedDeviceIndex = 0;

            SelectedDevice = devices[selectedDeviceIndex];

            if (SelectedDevice == null)
            {
                return;
            }

            if (CaptureMode == CaptureMode.Capture)
            {
                _soundIn = new WasapiCapture();
            }
            else
            {
                _soundIn = new WasapiLoopbackCapture();
            }

            _soundIn.Device = SelectedDevice;

            //Sample rate of audio
            int sampleRate = 16000;
            //bits per rate
            int bitsPerSample = 16;
            //chanels
            int channels = 1;


            //initialize the soundIn instance
            _soundIn.Initialize();

            //create a SoundSource around the the soundIn instance
            //this SoundSource will provide data, captured by the soundIn instance
            var soundInSource = new SoundInSource(_soundIn)
            {
                FillWithZeros = false
            };

            //create a source, that converts the data provided by the
            //soundInSource to any other format
            //in this case the "Fluent"-extension methods are being used
            IWaveSource convertedSource = soundInSource
                                          .ChangeSampleRate(sampleRate) // sample rate
                                          .ToSampleSource()
                                          .ToWaveSource(bitsPerSample); //bits per sample

            //channels=1 then we  need to create  mono audio
            convertedSource = convertedSource.ToMono();

            AudioToText audioToText = new AudioToText();

            audioToText.SetFolderPermission(_folderPath);

            //create a new wavefile
            waveWriter = new WaveWriter(fileName, convertedSource.WaveFormat);
            //register an event handler for the DataAvailable event of
            //the soundInSource
            //Important: use the DataAvailable of the SoundInSource
            //If you use the DataAvailable event of the ISoundIn itself
            //the data recorded by that event might won't be available at the
            //soundInSource yet
            soundInSource.DataAvailable += (s, e) =>
            {
                //read data from the converedSource
                //important: don't use the e.Data here
                //the e.Data contains the raw data provided by the
                //soundInSource which won't have your target format
                byte[] buffer = new byte[convertedSource.WaveFormat.BytesPerSecond / 2];
                int    read;

                //keep reading as long as we still get some data
                //if you're using such a loop, make sure that soundInSource.FillWithZeros is set to false
                while ((read = convertedSource.Read(buffer, 0, buffer.Length)) > 0)
                {
                    //write the read data to a file
                    // ReSharper disable once AccessToDisposedClosure
                    waveWriter.Write(buffer, 0, read);
                }
            };

            //we've set everything we need -> start capturing data
            objStopWatch.Start();
            _soundIn.Start();
        }
Exemplo n.º 12
0
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var openFileDialog = new OpenFileDialog()
            {
                Filter = CodecFactory.SupportedFilesFilterEn,
                Title = "Select a file..."
            };
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                Stop();

                const FftSize fftSize = FftSize.Fft4096;

                IWaveSource source = CodecFactory.Instance.GetCodec(openFileDialog.FileName);

                var spectrumProvider = new BasicSpectrumProvider(source.WaveFormat.Channels,
                    source.WaveFormat.SampleRate, fftSize);
                _lineSpectrum = new LineSpectrum(fftSize)
                {
                    SpectrumProvider = spectrumProvider,
                    UseAverage = true,
                    BarCount = 50,
                    BarSpacing = 2,
                    IsXLogScale = true,
                    ScalingStrategy = ScalingStrategy.Sqrt
                };
                _voicePrint3DSpectrum = new VoicePrint3DSpectrum(fftSize)
                {
                    SpectrumProvider = spectrumProvider,
                    UseAverage = true,
                    PointCount = 200,
                    IsXLogScale = true,
                    ScalingStrategy = ScalingStrategy.Sqrt
                };

                var notificationSource = new SingleBlockNotificationStream(source.ToSampleSource());
                notificationSource.SingleBlockRead += (s, a) => spectrumProvider.Add(a.Left, a.Right);

                _source = notificationSource.ToWaveSource(16);

                _soundOut = new WasapiOut();
                _soundOut.Initialize(_source.ToMono());
                _soundOut.Play();

                timer1.Start();

                propertyGridTop.SelectedObject = _lineSpectrum;
                propertyGridBottom.SelectedObject = _voicePrint3DSpectrum;
            }
        }
Exemplo n.º 13
0
        public override void Start()
        {
            if (_started)
            {
                Stop();
            }
            DataFlow dataFlow = (DataFlow)_speechSettings.SelectedDataFlowId;

            var devices = MMDeviceEnumerator.EnumerateDevices(dataFlow, DeviceState.Active);


            if (devices.Count - 1 < _speechSettings.InputDeviceIndex)
            {
                throw new Exception($" device Index {_speechSettings.InputDeviceIndex} is not avalibe");
            }

            if (dataFlow == DataFlow.Render)
            {
                var wasapiFormat = _waveFormatAdapter.WaveFormatFromCurrentSettings();
                _soundIn = new WasapiLoopbackCapture(100, wasapiFormat);
            }
            else
            {
                _soundIn = new WasapiCapture();
            }

            _soundIn.Device = devices[_speechSettings.InputDeviceIndex];

            _soundIn.Initialize();

            var wasapiCaptureSource = new SoundInSource(_soundIn)
            {
                FillWithZeros = false
            };

            _waveSource = wasapiCaptureSource
                          .ChangeSampleRate(_speechSettings.SampleRateValue) // sample rate
                          .ToSampleSource()
                          .ToWaveSource(_speechSettings.BitsPerSampleValue); //bits per sample;

            if (_speechSettings.ChannelValue == 1)
            {
                _waveSource = _waveSource.ToMono();
            }
            else
            {
                _waveSource = _waveSource.ToStereo();
            }


            wasapiCaptureSource.DataAvailable += (s, e) =>
            {
                //read data from the converedSource
                //important: don't use the e.Data here
                //the e.Data contains the raw data provided by the
                //soundInSource which won't have your target format
                byte[] buffer = new byte[_waveSource.WaveFormat.BytesPerSecond / 2];
                int    read;

                //keep reading as long as we still get some data
                //if you're using such a loop, make sure that soundInSource.FillWithZeros is set to false
                while ((read = _waveSource.Read(buffer, 0, buffer.Length)) > 0)
                {
                    SendData(buffer, read);
                }
            };

            _soundIn.Start();

            _started = true;
        }
        private WasapiCapture StartListeningOnLoopback()
        {
            const int GOOGLE_RATE            = 16000;
            const int GOOGLE_BITS_PER_SAMPLE = 16;
            const int GOOGLE_CHANNELS        = 1;

            CaptureMode captureMode = _captureMode;

            DataFlow dataFlow = captureMode == CaptureMode.Capture ? DataFlow.Capture : DataFlow.Render;

            var devices = MMDeviceEnumerator.EnumerateDevices(dataFlow, DeviceState.Active);

            Console.WriteLine("Please select devlice:");
            for (int i = 0; i < devices.Count; i++)
            {
                Console.WriteLine(i + ") " + devices[i].FriendlyName);
            }
            var deviceIndex = int.Parse(Console.ReadLine());

            var headphones = devices[deviceIndex];

            //using (WasapiCapture capture = new WasapiLoopbackCapture())
            _soundIn = captureMode == CaptureMode.Capture
                ? new WasapiCapture()
                : new WasapiLoopbackCapture();

            //if nessesary, you can choose a device here
            //to do so, simply set the device property of the capture to any MMDevice
            //to choose a device, take a look at the sample here: http://cscore.codeplex.com/

            _soundIn.Device = headphones;


            //initialize the selected device for recording
            _soundIn.Initialize();
            //create a SoundSource around the the soundIn instance
            //this SoundSource will provide data, captured by the soundIn instance
            _soundInSource = new SoundInSource(_soundIn)
            {
                FillWithZeros = false
            };

            //create a source, that converts the data provided by the
            //soundInSource to any other format
            //in this case the "Fluent"-extension methods are being used
            _convertedSource = _soundInSource
                               .ChangeSampleRate(GOOGLE_RATE)         // sample rate
                               .ToSampleSource()
                               .ToWaveSource(GOOGLE_BITS_PER_SAMPLE); //bits per sample

            var channels = GOOGLE_CHANNELS;

            //channels...
            var src = channels == 1 ? _convertedSource.ToMono() : _convertedSource.ToStereo();


            _soundInSource.DataAvailable += (sender, args) =>
            {
                //read data from the converedSource
                //important: don't use the e.Data here
                //the e.Data contains the raw data provided by the
                //soundInSource which won't have your target format
                byte[] buffer = new byte[_convertedSource.WaveFormat.BytesPerSecond / 2];
                int    read;

                //keep reading as long as we still get some data
                //if you're using such a loop, make sure that soundInSource.FillWithZeros is set to false
                while ((read = src.Read(buffer, 0, buffer.Length)) > 0)
                {
                    //write the read data to a file
                    // ReSharper disable once AccessToDisposedClosure
                    Debug.WriteLine($"Read {read} bytes");
                    _microphoneBuffer.Add(ByteString.CopyFrom(buffer, 0, read));

                    //w.Write(buffer, 0, read);
                }
            };



            return(_soundIn);
        }
Exemplo n.º 15
0
        // ReSharper disable once UnusedParameter.Local
        static void Main(string[] args)
        {
            //choose the capture mode
            Console.WriteLine("Select capturing mode:");
            Console.WriteLine("- 1: Capture");
            Console.WriteLine("- 2: LoopbackCapture");

            CaptureMode captureMode = (CaptureMode)ReadInteger(1, 2);
            DataFlow    dataFlow    = captureMode == CaptureMode.Capture ? DataFlow.Capture : DataFlow.Render;

            //---

            //select the device:
            var devices = MMDeviceEnumerator.EnumerateDevices(dataFlow, DeviceState.Active);

            if (!devices.Any())
            {
                Console.WriteLine("No devices found.");
                return;
            }

            Console.WriteLine("Select device:");
            for (int i = 0; i < devices.Count; i++)
            {
                Console.WriteLine("- {0:#00}: {1}", i, devices[i].FriendlyName);
            }
            int selectedDeviceIndex = ReadInteger(Enumerable.Range(0, devices.Count).ToArray());
            var device = devices[selectedDeviceIndex];

            //--- choose format
            Console.WriteLine("Enter sample rate:");
            int sampleRate;

            do
            {
                sampleRate = ReadInteger();
                if (sampleRate >= 100 && sampleRate <= 200000)
                {
                    break;
                }
                Console.WriteLine("Must be between 1kHz and 200kHz.");
            } while (true);

            Console.WriteLine("Choose bits per sample (8, 16, 24 or 32):");
            int bitsPerSample = ReadInteger(8, 16, 24, 32);

            //note: this sample does not support multi channel formats like surround 5.1,...
            //if this is required, the DmoChannelResampler class can be used
            Console.WriteLine("Choose number of channels (1, 2):");
            int channels = ReadInteger(1, 2);

            //---

            //start recording

            //create a new soundIn instance
            using (WasapiCapture soundIn = captureMode == CaptureMode.Capture
                ? new WasapiCapture()
                : new WasapiLoopbackCapture())
            {
                //optional: set some properties
                soundIn.Device = device;
                //...

                //initialize the soundIn instance
                soundIn.Initialize();

                //create a SoundSource around the the soundIn instance
                //this SoundSource will provide data, captured by the soundIn instance
                SoundInSource soundInSource = new SoundInSource(soundIn)
                {
                    FillWithZeros = false
                };

                //create a source, that converts the data provided by the
                //soundInSource to any other format
                //in this case the "Fluent"-extension methods are being used
                IWaveSource convertedSource = soundInSource
                                              .ChangeSampleRate(sampleRate) // sample rate
                                              .ToSampleSource()
                                              .ToWaveSource(bitsPerSample); //bits per sample

                //channels...
                using (convertedSource = channels == 1 ? convertedSource.ToMono() : convertedSource.ToStereo())
                {
                    //create a new wavefile
                    using (WaveWriter waveWriter = new WaveWriter("out.wav", convertedSource.WaveFormat))
                    {
                        //register an event handler for the DataAvailable event of
                        //the soundInSource
                        //Important: use the DataAvailable of the SoundInSource
                        //If you use the DataAvailable event of the ISoundIn itself
                        //the data recorded by that event might won't be available at the
                        //soundInSource yet
                        soundInSource.DataAvailable += (s, e) =>
                        {
                            //read data from the converedSource
                            //important: don't use the e.Data here
                            //the e.Data contains the raw data provided by the
                            //soundInSource which won't have your target format
                            byte[] buffer = new byte[convertedSource.WaveFormat.BytesPerSecond / 2];
                            int    read;

                            //keep reading as long as we still get some data
                            //if you're using such a loop, make sure that soundInSource.FillWithZeros is set to false
                            while ((read = convertedSource.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                //write the read data to a file
                                // ReSharper disable once AccessToDisposedClosure
                                waveWriter.Write(buffer, 0, read);
                            }
                        };

                        //we've set everything we need -> start capturing data
                        soundIn.Start();

                        Console.WriteLine("Capturing started ... press any key to stop.");
                        Console.ReadKey();

                        soundIn.Stop();
                    }
                }
            }

            Process.Start("out.wav");
        }
Exemplo n.º 16
0
        static void Main(string[] args)
        {
            WaveFormat waveFormat = new WaveFormat(44100, 16, 1);

            Oscillator freqOsc      = new Oscillator(Oscillator.WaveType.SineWave, waveFormat.SampleRate, new ConstantScalar(0.1f), new ConstantScalar(80.0f), new ConstantScalar(0), new ConstantScalar(100.0f));
            Oscillator ampOscVel    = new Oscillator(Oscillator.WaveType.SineWave, waveFormat.SampleRate, new ConstantScalar(0.05f), new ConstantScalar(8.0f), new ConstantScalar(0.5f), new ConstantScalar(8.0f));
            Oscillator ampOsc       = new Oscillator(Oscillator.WaveType.SawtoothWave, waveFormat.SampleRate, ampOscVel, new ConstantScalar(0.5f), new ConstantScalar(0), new ConstantScalar(1.1f));
            Oscillator variableFreq = new Oscillator(Oscillator.WaveType.SineWave, waveFormat.SampleRate, freqOsc, ampOsc, new ConstantScalar(0), new ConstantScalar(0));

            ScalarPassthrough scalarPassthru = new ScalarPassthrough(waveFormat, variableFreq);

            NoiseGenerator noiseGen  = new NoiseGenerator(waveFormat, NoiseGenerator.NoiseType.WhiteNoise);
            Oscillator     freqsweep = new Oscillator(Oscillator.WaveType.SineWave, waveFormat.SampleRate, new ConstantScalar(0.1f), new ConstantScalar(200), new ConstantScalar(0), new ConstantScalar(440));
            Oscillator     qsweep    = new Oscillator(Oscillator.WaveType.SineWave, waveFormat.SampleRate, new ConstantScalar(1.0f), new ConstantScalar(0.9f), new ConstantScalar(0), new ConstantScalar(1.0f)); //new ConstantScalar((float)(1.0 / Math.Sqrt(2)));
            //Oscillator gainSweep = new Oscillator(Oscillator.WaveType.TriangleWave, waveFormat.SampleRate, new ConstantScalar(0.025f), new ConstantScalar(2), new ConstantScalar(0), new ConstantScalar(6));
            ConstantScalar gainSweep = new ConstantScalar(6);

            SampleProcessor.SampleProcessor filter = new SampleProcessor.NotchFilter(waveFormat, freqsweep, qsweep, gainSweep, scalarPassthru);


            // distortion "pedal" on a minimally modified hard body electric guitar signal
            Oscillator     gainOsc     = new Oscillator(Oscillator.WaveType.SineWave, waveFormat.SampleRate, new ConstantScalar(0.5f), new ConstantScalar(2), new ConstantScalar(0), new ConstantScalar(5));
            Oscillator     cutoffOsc   = new Oscillator(Oscillator.WaveType.SineWave, waveFormat.SampleRate, new ConstantScalar(0.95f), new ConstantScalar(3), new ConstantScalar(0), new ConstantScalar(4));
            ConstantScalar cutoff      = new ConstantScalar(0.2f);
            IWaveSource    cleanguitar = CodecFactory.Instance.GetCodec(@"..\..\sampledata\guitar-sample.mp3"); // sample signal from single-pickup electric guitar. Recorded 8/14/20.
            IReadableAudioSource <float> convertedguitar = cleanguitar.ToMono().ToSampleSource();

            SampleProcessor.DistortionEffect distortion   = new SampleProcessor.DistortionEffect(waveFormat, gainOsc, cutoff, convertedguitar);
            SampleProcessor.SampleProcessor  reverbEffect = new SampleProcessor.ReverbEffect(waveFormat, new ConstantScalar(0.4f), new ConstantScalar(0.5f), waveFormat.SampleRate, distortion);

            BasicAudioController basicAudioController = new BasicAudioController(GetSoundOut(), 1, 44100);

            basicAudioController.addSource((ISampleSource)reverbEffect);
            basicAudioController.startPlaying();

            Console.ReadKey();
            basicAudioController.stopPlaying();
            return;

            MIDI.MIDIData data = MIDI.MIDIFileReader.readFile(@"..\..\sampledata\MIDI_sample.mid");

            MIDI.MIDIData testdata = new MIDI.MIDIData();
            testdata.format       = 0;
            testdata.timing       = MIDI.TimingScheme.TimeCode;
            testdata.timecode_fps = 24;
            testdata.timecode_sfr = 4;
            testdata.ntracks      = 1;
            testdata.tracks.Add(new MIDI.MIDITrack());
            MIDI.MIDIEvent event0 = new MIDI.MIDIEvent();
            MIDI.MIDIEvent event1 = new MIDI.MIDIEvent();

            event0.delta = 4 * 24 * 5; // wait 5 seconds from start
            event1.delta = 4 * 24 * 2; // 2 seconds

            //event0.type = MIDI.EventType.MIDIEvent;
            //event0.midieventtype = MIDI.MIDIEventType.NoteOn;
            //event0.val1 = 0; // channel 0
            //event0.val2 = 60; // middle C
            //event0.val3 = 1;

            //event1.type = MIDI.EventType.MIDIEvent;
            //event1.midieventtype = MIDI.MIDIEventType.NoteOff;
            //event1.val1 = 0; // channel 0
            //event1.val2 = 60; // middle C
            //event1.val3 = 1;

            //testdata.tracks[0].events.Add(event0);
            //testdata.tracks[0].events.Add(event1);


            MIDI.MIDIPlayer player = new MIDI.MIDIPlayer(data);
            Console.WriteLine("Track 1 events:");
            player.playTrack(1);

            Console.ReadKey();
            return;

            MIDIAudioController audioController = new MIDIAudioController(GetSoundOut());

            ChromaticScale.ChromaticScale scale = new ChromaticScale.ChromaticScale();
            audioController.startPlaying();
            SampleSource.WaveGenerator.WaveType wavetype = WaveGenerator.WaveType.SineWave;

            Console.ReadKey(); // wait for input
            for (int i = 0; i < scale.notes.Count(); i++)
            {
                float freq = scale.notes[i].base_freq / 2;
                Console.WriteLine(scale.notes[i].identifier[0] + " - " + freq + " - " + wavetype);
                audioController.updatePlaying(freq, wavetype);
                Console.ReadKey(); // wait for input

                wavetype = Next(wavetype);
            }
            for (int i = 0; i < scale.notes.Count(); i++)
            {
                Console.WriteLine(scale.notes[i].identifier[0] + " - " + scale.notes[i].base_freq.ToString() + " - " + wavetype);
                audioController.updatePlaying(scale.notes[i].base_freq, wavetype);
                Console.ReadKey(); // wait for input
                wavetype = Next(wavetype);
            }
            for (int i = 0; i < scale.notes.Count(); i++)
            {
                float freq = scale.notes[i].base_freq * 2;
                Console.WriteLine(scale.notes[i].identifier[0] + " - " + freq + " - " + wavetype);
                audioController.updatePlaying(freq, wavetype);
                Console.ReadKey(); // wait for input
                wavetype = Next(wavetype);
            }

            audioController.stopPlaying();
            audioController.Dispose();
        }
Exemplo n.º 17
0
        public void Record(string deviceName, string audioFilePath = @"C:\Temp\output.wav")
        {
            _timer = new Stopwatch();
            _timer.Start();

            // choose the capture mod
            CaptureMode captureMode = CaptureMode.LoopbackCapture;
            DataFlow    dataFlow    = captureMode == CaptureMode.Capture ? DataFlow.Capture : DataFlow.Render;

            //select the device:
            var devices = MMDeviceEnumerator.EnumerateDevices(dataFlow, DeviceState.Active);

            if (!devices.Any())
            {
                Console.WriteLine("### No devices found.");
                return;
            }

            Console.WriteLine($"### Using device {deviceName}");
            var device = devices.First(d => d.FriendlyName.Equals(deviceName));

            //start recording
            //create a new soundIn instance
            _soundIn = captureMode == CaptureMode.Capture
                ? new WasapiCapture()
                : new WasapiLoopbackCapture();


            //optional: set some properties
            _soundIn.Device = device;


            //initialize the soundIn instance
            _soundIn.Initialize();

            //create a SoundSource around the the soundIn instance
            //this SoundSource will provide data, captured by the soundIn instance
            SoundInSource soundInSource = new SoundInSource(_soundIn)
            {
                FillWithZeros = false
            };

            //create a source, that converts the data provided by the
            //soundInSource to any other format
            //in this case the "Fluent"-extension methods are being used
            _convertedSource = soundInSource
                               .ChangeSampleRate(SampleRate) // sample rate
                               .ToSampleSource()
                               .ToWaveSource(BitsPerSample); //bits per sample

            //channels...
            _convertedSource = _convertedSource.ToMono();

            //create a new wavefile
            _waveWriter = new WaveWriter(audioFilePath, _convertedSource.WaveFormat);

            //register an event handler for the DataAvailable event of
            //the soundInSource
            //Important: use the DataAvailable of the SoundInSource
            //If you use the DataAvailable event of the ISoundIn itself
            //the data recorded by that event might won't be available at the
            //soundInSource yet
            soundInSource.DataAvailable += (s, e) =>
            {
                //read data from the converedSource
                //important: don't use the e.Data here
                //the e.Data contains the raw data provided by the
                //soundInSource which won't have your target format
                byte[] buffer = new byte[_convertedSource.WaveFormat.BytesPerSecond / 2];
                int    read;

                //keep reading as long as we still get some data
                //if you're using such a loop, make sure that soundInSource.FillWithZeros is set to false
                while ((read = _convertedSource.Read(buffer, 0, buffer.Length)) > 0)
                {
                    //write the read data to a file
                    // ReSharper disable once AccessToDisposedClosure
                    _waveWriter.Write(buffer, 0, read);
                }
            };

            //we've set everything we need -> start capturing data
            _soundIn.Start();
            Console.WriteLine($"### RECORDING {audioFilePath}");

            while (_timer.ElapsedMilliseconds / 1000 < 15 && _timer.IsRunning)
            {
                Thread.Sleep(500);
            }

            Console.WriteLine("### STOP RECORDING");
            _soundIn.Stop();
            _timer.Stop();

            _waveWriter.Dispose();
            _convertedSource.Dispose();
            _soundIn.Dispose();

            AudioFileCaptured?.Invoke(this, new AudioRecorderEventArgs()
            {
                AudioFilePath = audioFilePath
            });
        }
Exemplo n.º 18
0
        // ReSharper disable once UnusedParameter.Local
        static void Main(string[] args)
        {
            CaptureMode captureMode;

            if (Boolean.Parse(ConfigurationManager.AppSettings["defaultToLoopback"]))
            {
                captureMode = CaptureMode.LoopbackCapture;
            }
            else
            {
                Console.WriteLine("Select capturing mode:");
                Console.WriteLine("- 1: Capture");
                Console.WriteLine("- 2: LoopbackCapture");

                captureMode = (CaptureMode)ReadInteger(1, 2);
            }
            DataFlow dataFlow = captureMode == CaptureMode.Capture ? DataFlow.Capture : DataFlow.Render;

            var devices = MMDeviceEnumerator.EnumerateDevices(dataFlow, DeviceState.Active);

            if (!devices.Any())
            {
                Console.WriteLine("No devices found.");
                return;
            }
            MMDevice device;

            if (devices.Count == 1)
            {
                device = devices[0];
            }
            else
            {
                Console.WriteLine("Select device:");
                for (int i = 0; i < devices.Count; i++)
                {
                    Console.WriteLine("- {0:#00}: {1}", i, devices[i].FriendlyName);
                }
                int selectedDeviceIndex = ReadInteger(Enumerable.Range(0, devices.Count).ToArray());
                device = devices[selectedDeviceIndex];
            }

            int sampleRate    = Int32.Parse(ConfigurationManager.AppSettings["sampleRate"]);
            int bitsPerSample = Int32.Parse(ConfigurationManager.AppSettings["bitsPerSample"]);
            int channels      = 1;

            //create a new soundIn instance
            using (WasapiCapture soundIn = captureMode == CaptureMode.Capture
                ? new WasapiCapture()
                : new WasapiLoopbackCapture())
            {
                //optional: set some properties
                soundIn.Device = device;
                //...

                //initialize the soundIn instance
                soundIn.Initialize();

                //create a SoundSource around the the soundIn instance
                //this SoundSource will provide data, captured by the soundIn instance
                SoundInSource soundInSource = new SoundInSource(soundIn)
                {
                    FillWithZeros = false
                };

                //create a source, that converts the data provided by the
                //soundInSource to any other format
                //in this case the "Fluent"-extension methods are being used
                IWaveSource convertedSource = soundInSource
                                              .ChangeSampleRate(sampleRate) // sample rate
                                              .ToSampleSource()
                                              .ToWaveSource(bitsPerSample); //bits per sample

                //channels...
                using (convertedSource = channels == 1 ? convertedSource.ToMono() : convertedSource.ToStereo())
                {
                    //create a new wavefile
                    var fileName = "out-" + DateTime.UtcNow.ToString("yyyy-MM-ddTHH-mm-ss") + ".wav";
                    using (WaveWriter waveWriter = new WaveWriter(fileName, convertedSource.WaveFormat))
                    {
                        //register an event handler for the DataAvailable event of
                        //the soundInSource
                        //Important: use the DataAvailable of the SoundInSource
                        //If you use the DataAvailable event of the ISoundIn itself
                        //the data recorded by that event might won't be available at the
                        //soundInSource yet
                        soundInSource.DataAvailable += (s, e) =>
                        {
                            //read data from the converedSource
                            //important: don't use the e.Data here
                            //the e.Data contains the raw data provided by the
                            //soundInSource which won't have your target format
                            byte[] buffer = new byte[convertedSource.WaveFormat.BytesPerSecond / 2];
                            int    read;

                            //keep reading as long as we still get some data
                            //if you're using such a loop, make sure that soundInSource.FillWithZeros is set to false
                            while ((read = convertedSource.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                //write the read data to a file
                                // ReSharper disable once AccessToDisposedClosure
                                waveWriter.Write(buffer, 0, read);
                            }
                        };

                        //we've set everything we need -> start capturing data
                        soundIn.Start();

                        Console.WriteLine("Capturing started ... press any key to stop.");
                        Console.ReadKey();

                        soundIn.Stop();
                    }
                }
            }
        }
Exemplo n.º 19
0
        static void writeSpeakersToWav(string[] args)
        {
            const int GOOGLE_RATE            = 16000;
            const int GOOGLE_BITS_PER_SAMPLE = 16;
            const int GOOGLE_CHANNELS        = 1;
            const int EARPHONES = 5;

            CaptureMode captureMode = CaptureMode.LoopbackCapture;

            DataFlow dataFlow = captureMode == CaptureMode.Capture ? DataFlow.Capture : DataFlow.Render;

            var devices = MMDeviceEnumerator.EnumerateDevices(dataFlow, DeviceState.Active);

            foreach (var d in devices)
            {
                Console.WriteLine("- {0:#00}: {1}", d, d.FriendlyName);
            }
            var headphones = devices.First(x => x.FriendlyName.StartsWith("small"));

            //using (WasapiCapture capture = new WasapiLoopbackCapture())
            using (WasapiCapture soundIn = captureMode == CaptureMode.Capture
                ? new WasapiCapture()
                : new WasapiLoopbackCapture())
            {
                //if nessesary, you can choose a device here
                //to do so, simply set the device property of the capture to any MMDevice
                //to choose a device, take a look at the sample here: http://cscore.codeplex.com/

                soundIn.Device = headphones;

                Console.WriteLine("Waiting, press any key to start");
                Console.ReadKey();
                //initialize the selected device for recording
                soundIn.Initialize();

                //create a SoundSource around the the soundIn instance
                //this SoundSource will provide data, captured by the soundIn instance
                SoundInSource soundInSource = new SoundInSource(soundIn)
                {
                    FillWithZeros = false
                };

                //create a source, that converts the data provided by the
                //soundInSource to any other format
                //in this case the "Fluent"-extension methods are being used
                IWaveSource convertedSource = soundInSource
                                              .ChangeSampleRate(GOOGLE_RATE)         // sample rate
                                              .ToSampleSource()
                                              .ToWaveSource(GOOGLE_BITS_PER_SAMPLE); //bits per sample

                var channels = GOOGLE_CHANNELS;

                //channels...
                using (convertedSource = channels == 1 ? convertedSource.ToMono() : convertedSource.ToStereo())
                    //create a wavewriter to write the data to
                    using (WaveWriter w = new WaveWriter("dump.wav", convertedSource.WaveFormat))
                    {
                        //setup an eventhandler to receive the recorded data
                        //register an event handler for the DataAvailable event of
                        //the soundInSource
                        //Important: use the DataAvailable of the SoundInSource
                        //If you use the DataAvailable event of the ISoundIn itself
                        //the data recorded by that event might won't be available at the
                        //soundInSource yet
                        soundInSource.DataAvailable += (s, e) =>
                        {
                            //read data from the converedSource
                            //important: don't use the e.Data here
                            //the e.Data contains the raw data provided by the
                            //soundInSource which won't have your target format
                            byte[] buffer = new byte[convertedSource.WaveFormat.BytesPerSecond / 2];
                            int    read;

                            //keep reading as long as we still get some data
                            //if you're using such a loop, make sure that soundInSource.FillWithZeros is set to false
                            while ((read = convertedSource.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                //write the read data to a file
                                // ReSharper disable once AccessToDisposedClosure
                                w.Write(buffer, 0, read);
                            }
                        };


                        //start recording
                        soundIn.Start();

                        Console.WriteLine("Started, press any key to stop");
                        Console.ReadKey();

                        //stop recording
                        soundIn.Stop();
                    }
            }
        }
Exemplo n.º 20
0
        public async Task AudioStreamCommand([
                                                 Summary("Voice Channel name")]
                                             IVoiceChannel channel = null,
                                             [Summary("Number of audio channels, 1 for mono, 2 for stereo (Default)")]
                                             int nAudioChannels = 2,
                                             [Summary("Sample rate in hertz, 48000 (Default)")]
                                             int sampleRate = 48000,
                                             [Summary("Number of bits per sample, 16 (Default)")]
                                             int bitsPerSample = 16)
        {
            var connection = await channel.ConnectAsync();

            var dstream = connection.CreatePCMStream(AudioApplication.Mixed);

            using (WasapiCapture soundIn = new WasapiLoopbackCapture())
            {
                //initialize the soundIn instance
                soundIn.Initialize();

                //create a SoundSource around the the soundIn instance
                //this SoundSource will provide data, captured by the soundIn instance
                SoundInSource soundInSource = new SoundInSource(soundIn)
                {
                    FillWithZeros = false
                };

                //create a source, that converts the data provided by the
                //soundInSource to any other format
                //in this case the "Fluent"-extension methods are being used
                IWaveSource convertedSource = soundInSource
                                              .ChangeSampleRate(sampleRate) // sample rate
                                              .ToSampleSource()
                                              .ToWaveSource(bitsPerSample); //bits per sample
                //int channels = 2;
                //channels...
                using (convertedSource = nAudioChannels == 1 ? convertedSource.ToMono() : convertedSource.ToStereo())
                {
                    //register an event handler for the DataAvailable event of
                    //the soundInSource
                    //Important: use the DataAvailable of the SoundInSource
                    //If you use the DataAvailable event of the ISoundIn itself
                    //the data recorded by that event might won't be available at the
                    //soundInSource yet
                    soundInSource.DataAvailable += (s, e) =>
                    {
                        //read data from the converedSource
                        //important: don't use the e.Data here
                        //the e.Data contains the raw data provided by the
                        //soundInSource which won't have your target format
                        byte[] buffer = new byte[convertedSource.WaveFormat.BytesPerSecond / 2];
                        int    read;

                        //keep reading as long as we still get some data
                        //if you're using such a loop, make sure that soundInSource.FillWithZeros is set to false
                        while ((read = convertedSource.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            //write the read data to a file
                            // ReSharper disable once AccessToDisposedClosure
                            dstream.Write(buffer, 0, read);
                        }
                    };

                    //we've set everything we need -> start capturing data
                    soundIn.Start();

                    Console.WriteLine("Capturing started ... press any key to stop.");
                    Console.ReadKey();
                    soundIn.Stop();
                }
            }
        }