Пример #1
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            if (deviceslist.SelectedItems.Count <= 0)
                return;

            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "WAV (*.wav)|*.wav";
            sfd.Title = "Speichern";
            sfd.FileName = String.Empty;
            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                _waveIn = new WaveInEvent(new WaveFormat(44100, 16, _selectedDevice.Channels));
                _waveIn.Device = deviceslist.SelectedItems[0].Index;

                _waveIn.Initialize();
                _waveIn.Start();

                var waveInToSource = new SoundInSource(_waveIn);

                _source = waveInToSource;
                var notifyStream = new SingleBlockNotificationStream(_source);
                notifyStream.SingleBlockRead += OnNotifyStream_SingleBlockRead;

                _source = notifyStream.ToWaveSource(16);
                _writerBuffer = new byte[_source.WaveFormat.BytesPerSecond];

                _writer = new WaveWriter(File.OpenWrite(sfd.FileName), _source.WaveFormat);
                waveInToSource.DataAvailable += OnNewData;

                btnStart.Enabled = false;
                btnStop.Enabled = true;
            }
        }
Пример #2
0
        /// <summary>
        /// Record sound made in Mic and save it to a wave file
        /// </summary>
        /// <param name="wavefile">name of the wave file with extension</param>
        public void CaptureMicToWave(string wavefile)
        {
            int i = 0;
            string extension = ".wav";

            foreach (var device in WaveIn.Devices)
            {
                _waveIn = new WaveInEvent(new WaveFormat(44100, 16, device.Channels));
                _waveIn.Device = i++;

                _waveIn.Initialize();
                _waveIn.Start();

                var waveInToSource = new SoundInSource(_waveIn);

                _source = waveInToSource;
                var notifyStream = new SingleBlockNotificationStream(_source);

                _source = notifyStream.ToWaveSource(16);
                _writerBuffer = new byte[_source.WaveFormat.BytesPerSecond];

                wavefile = string.Format("{0}{1}{2}", wavefile.Remove(wavefile.LastIndexOf(extension) - (i > 1 ? 1 : 0)), i, extension);
                _writer = new WaveWriter(wavefile, _source.WaveFormat);
                waveInToSource.DataAvailable += (s, e) =>
                {
                    int read = 0;
                    while ((read = _source.Read(_writerBuffer, 0, _writerBuffer.Length)) > 0)
                    {
                        _writer.Write(_writerBuffer, 0, read);
                    }
                };
            }
        }
Пример #3
0
        static void Main(string[] args)
        {
            using (var wasapiCapture = new WasapiLoopbackCapture())
            {
                wasapiCapture.Initialize();
                var wasapiCaptureSource = new SoundInSource(wasapiCapture);
                using(var stereoSource = wasapiCaptureSource.ToStereo())
                {
                    //using (var writer = MediaFoundationEncoder.CreateWMAEncoder(stereoSource.WaveFormat, "output.wma"))
                    using(var writer = new WaveWriter("output.wav", stereoSource.WaveFormat))
                    {
                        byte[] buffer = new byte[stereoSource.WaveFormat.BytesPerSecond];
                        wasapiCaptureSource.DataAvailable += (s, e) =>
                        {
                            int read = stereoSource.Read(buffer, 0, buffer.Length);
                            writer.Write(buffer, 0, read);
                        };

                        wasapiCapture.Start();

                        Console.ReadKey();

                        wasapiCapture.Stop();
                    }
                }
            }
        }
Пример #4
0
        public void SoundInToSoundOutTest_Wasapi()
        {
            for (int i = 0; i < 10; i++)
            {
                var waveIn = new WasapiCapture();
                waveIn.Initialize();
                waveIn.Start();

                var waveInToSource = new SoundInSource(waveIn) { FillWithZeros = true };

                var soundOut = new WasapiOut();
                soundOut.Initialize(waveInToSource);
                soundOut.Play();

                Thread.Sleep(2000);

                Assert.AreEqual(PlaybackState.Playing, soundOut.PlaybackState);

                soundOut.Dispose();
                waveIn.Dispose();
            }
        }
Пример #5
0
        /** Initializes the realtime audio processing handlers */
        public void BeginRecording()
        {
            // recoreds output data from wasapi loopback sound card.
            using (wasapiCapture = new WasapiLoopbackCapture())
            {
                wasapiCapture.Initialize();
                wasapiCaptureSource = new SoundInSource(wasapiCapture);

                // TODO: Stereo or Mono?
                using (var stereoSource = wasapiCaptureSource.ToStereo())
                {
                    // creates the spectrum Provider (Our own FFTProvider)
                    provider = new BasicSpectrumProvider(stereoSource.WaveFormat.Channels, stereoSource.WaveFormat.SampleRate, fftSize);
                    // creates the handler that uses the SpectrumProvider.
                    var handler = new FFTHandler(FftSize.Fft4096)
                    {
                        SpectrumProvider = provider,
                        UseAverage = true,
                        height = 100,
                        BarCount = 10,
                        BarSpacing = 2,
                        IsXLogScale = true,
                        ScalingStrategy = ScalingStrategy.Sqrt
                    };

                    // notifies the spectrum provider each block read
                    var notificationSource = new SingleBlockNotificationStream(wasapiCaptureSource.ToSampleSource());
                    notificationSource.SingleBlockRead += (s, a) => provider.Add(a.Left, a.Right);
                    var wsrc = notificationSource.ToWaveSource();

                    // reads through the wave source as it is playing
                    // This is the key to getting the realtime music.
                    byte[] buffer = new byte[wsrc.WaveFormat.BytesPerSecond];
                    wasapiCaptureSource.DataAvailable += (s, e) =>
                    {
                        int read = wsrc.Read(buffer, 0, buffer.Length);

                    };

                    // starts the listening.
                    wasapiCapture.Start();

                    // gathers the data and sends it to the handler in a loop.
                    var fftBuffer = new float[(int)fftSize];
                    while (true)
                    {
                        if (provider.GetFftData(fftBuffer))
                        {

                            Console.Clear();
                            handler.CreateSpectrumLineInternal(fftBuffer, 100);
                        }
                    }

                    // Stops Listening.
                    wasapiCapture.Stop();
                }
            }

            //    bool Data_Available = false;
            //    Double[] Audio_Samples = new Double[0];

            //    var waveIn = new WasapiLoopbackCapture();
            //    waveIn.DataAvailable += ( sender, e) =>
            //{
            //    Int32 sample_count = e.ByteCount / (waveIn.WaveFormat.BitsPerSample / 8);
            //    Single[] data = new Single[sample_count];

            //    for (int i = 0; i < sample_count; ++i)
            //    {
            //        data[i] = BitConverter.ToSingle(e.Data, i * 4);
            //    }

            //    int j = 0;
            //    Audio_Samples = new Double[sample_count / 2];
            //    for (int sample = 0; sample < data.Length; sample += 2)
            //    {
            //        Audio_Samples[j] = (Double)data[sample];
            //        Audio_Samples[j] += (Double)data[sample + 1];
            //        ++j;

            //        Console.WriteLine(Audio_Samples[j].ToString());
            //    }

            //    Data_Available = true;
            //};
            //    waveIn.Initialize();
            //    //waveIn.Stopped += OnRecordingStopped;
            //    waveIn.Start();

            //    while (true)
            //    {
            //        if (Data_Available)
            //        {
            //            Data_Available = false;
            //            //Console.WriteLine(Audio_Samples.ToString());
            //        }
            //    }

            //using (WasapiCapture capture = 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/

            //    //initialize the selected device for recording
            //    capture.Initialize();

            //    var eq = new Equalizer(new SoundInSource(capture));

            //    var fft = new FftProvider(3, FftSize.Fft1024);

            //    var tenb = Equalizer.Create10BandEqualizer(new SoundInSource(capture));

            //create a wavewriter to write the data to
            //using (WaveWriter w = new WaveWriter("dump.wav", capture.WaveFormat))
            //{

            //    //setup an eventhandler to receive the recorded data
            //    capture.DataAvailable += (s, e) =>
            //    {
            //            //save the recorded audio
            //            w.Write(e.Data, e.Offset, e.ByteCount);

            //    };

            //    Console.WriteLine("starting...");

            //    //start recording
            //    capture.Start();

            //    Console.ReadKey();

            //    capture.Stop();

            //}
        }
Пример #6
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");
        }
Пример #7
0
        private void StartCapture(string fileName)
        {
            if (SelectedDevice == null)
                return;

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

            _soundIn.Device = SelectedDevice;
            _soundIn.Initialize();

            var soundInSource = new SoundInSource(_soundIn);
            var singleBlockNotificationStream = new SingleBlockNotificationStream(soundInSource.ToSampleSource());
            _finalSource = singleBlockNotificationStream.ToWaveSource();
            _writer = new WaveWriter(fileName, _finalSource.WaveFormat);

            byte[] buffer = new byte[_finalSource.WaveFormat.BytesPerSecond / 2];
            soundInSource.DataAvailable += (s, e) =>
            {
                int read;
                while((read = _finalSource.Read(buffer, 0, buffer.Length)) > 0)
                    _writer.Write(buffer, 0, read);
            };

            singleBlockNotificationStream.SingleBlockRead += SingleBlockNotificationStreamOnSingleBlockRead;

            _soundIn.Start();
        }