Exemple #1
0
        public static void WriteToFile(string filename, IWaveSource source, bool deleteFileIfAlreadyExists,
                                       int maxlength = -1)
        {
            if (deleteFileIfAlreadyExists && File.Exists(filename))
            {
                File.Delete(filename);
            }

            int r      = 0;
            var buffer = new byte[source.WaveFormat.BytesPerSecond];

            using (var w = new WaveWriter(filename, source.WaveFormat))
            {
                int read;
                while ((read = source.Read(buffer, 0, buffer.Length)) > 0)
                {
                    w.Write(buffer, 0, read);
                    r += read;
                    if (maxlength != -1 && r > maxlength)
                    {
                        break;
                    }
                }
            }
        }
Exemple #2
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();
                    }
                }
            }
        }
Exemple #3
0
        public static void WriteToFile(string filename, IWaveSource source, bool deleteIfExists, int maxlength = -1)
        {
            if (deleteIfExists && File.Exists(filename))
                File.Delete(filename);

            int read = 0;
            int r = 0;
            byte[] buffer = new byte[source.WaveFormat.BytesPerSecond];
            using (var w = new WaveWriter(filename, source.WaveFormat))
            {
                while ((read = source.Read(buffer, 0, buffer.Length)) > 0)
                {
                    w.Write(buffer, 0, read);
                    r += read;
                    if (maxlength != -1 && r > maxlength)
                        break;
                }
            }
        }
Exemple #4
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");
        }
        void StopCapture(bool cancel)
        {
            var w = _writer;
            _writer = null;
            lock (w) w.Dispose();

            if (cancel) {
                File.Delete(_recordFileName);
                _tickList.Clear();
                Console.WriteLine("Aborted.");
                return;
            }

            StringBuilder fileContents = new StringBuilder();
            long sum = 0;
            for (int i = 0; i < _tickList.Count; i++) {
                if (i > 0) sum += _tickList[i] - _tickList[i - 1];
                fileContents.AppendLine((_tickList[i] - _recordStartTime - _endToEndLatency).ToString());
            }
            File.WriteAllText(
                Path.Combine(_destinationFolder, _recordStartSystemTimestamp.ToString("yyyyddMMHHmmssfff") + ".beats.txt"), 
                fileContents.ToString()
            );

            sum = sum / (_tickList.Count - 1);
            var bpm = 1 / ((double)sum / 1000 / 10000) * 60;
            Console.WriteLine("Average bpm: " + bpm);
            _tickList.Clear();
            _recordStartTime = 0;
        }
 void StartCapture()
 {
     _recordStartSystemTimestamp = DateTime.Now;
     _recordFileName = Path.Combine(_destinationFolder, _recordStartSystemTimestamp.ToString("yyyyddMMHHmmssfff") + ".wav");
     _writer = new WaveWriter(
         _recordFileName, 
         _capture.WaveFormat
     );
 }
Exemple #7
0
        /// <summary>
        /// Capture the audio outputed by the soundcard to a wave file.
        /// The sound you ear is recorded and saved to [wavefile].wav
        /// </summary>
        /// <param name="wavefile">name of the wave file with extension</param>
        /// <param name="captureSilence">if true record blank sounds</param>
        public void CaptureSpeakersToWave(string wavefile, bool captureSilence)
        {
            _capture = new WasapiLoopbackCapture();

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

            //create a wavewriter to write the data to
            _waveWriter = new WaveWriter(wavefile, _capture.WaveFormat);

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

            //start recording
            _capture.Start();

            if (captureSilence)
            {
                CaptureSilence();
            }
        }
Exemple #8
0
        /// <summary>
        /// stop audio capture started with CaptureAudioToWave
        /// </summary>
        public void UnCaptureSpeakersToWave()
        {
            //Stop silence recording
            if (_soundSilenceOut != null)
            {
                _soundSilenceOut.Stop();
                _soundSilenceOut.Dispose();
                _soundSilenceSource.Dispose();
                _soundSilenceOut = null;
                _soundSilenceSource = null;
            }

            //stop recording
            _capture.Stop();
            _waveWriter.Dispose();
            _waveWriter = null;

            _capture.Dispose();
            _capture = null;
        }