Esempio n. 1
0
 /// <summary>
 /// 启动录音
 /// </summary>
 public void Start()
 {
     audioStream = new MemoryStream();
     //WaveFileWriter with ignoredisposesream memorystream
     waveWriter = new WaveFileWriter(new IgnoreDisposeStream(audioStream), wave.WaveFormat);
     wave.StartRecording();
 }
Esempio n. 2
0
        private void recordBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (WaveIn.DeviceCount == 0)
                {
                    throw new Exception("Cannot detect microphone.");
                }

                _selectedFile = userDirPath + userName + ".wav";

                bool exist = File.Exists(_selectedFile);
                if (!exist)
                {
                    _fileWriter = new NAudio.Wave.WaveFileWriter(_selectedFile, _waveIn.WaveFormat);
                    _waveIn.StartRecording();

                    Title = String.Format("Recording...");
                    recordBtn.IsEnabled     = false;
                    stopRecordBtn.IsEnabled = true;
                }
                else
                {
                    MessageBox.Show("You have already registered your voice.");
                    faceIdentifyBtn.IsEnabled = true;
                }
                GC.Collect();
            }
            catch (Exception ex)
            {
                recordBtn.IsEnabled = true;
                Console.WriteLine("Error: " + ex.Message);
                GC.Collect();
            }
        }
        private Task Start()
        {
            IsRecording = true;
            //if (!IsRecording)
            {
                tempFile = Path.GetTempFileName();
                File.WriteAllBytes(tempFile, new byte[0]);

                ChangeFile();

                IsRecording = true;
                done        = false;

                return(Task.Run(() =>
                {
                    WaveIn.StartRecording();

                    while (IsRecording)
                    {
                        Thread.Sleep(0);
                    }

                    WaveIn.StopRecording();
                    done = true;
                }));
            }
            //return null;
        }
Esempio n. 4
0
 //Начинаем запись - обработчик нажатия кнопки
 private void button1_Click(object sender, EventArgs e)
 {
     try
     {
         MessageBox.Show("Start Recording");
         waveIn = new WaveIn();
         //Дефолтное устройство для записи (если оно имеется)
         //встроенный микрофон ноутбука имеет номер 0
         waveIn.DeviceNumber = 0;
         //Прикрепляем к событию DataAvailable обработчик, возникающий при наличии записываемых данных
         waveIn.DataAvailable += waveIn_DataAvailable;
         //Прикрепляем обработчик завершения записи
         waveIn.RecordingStopped += waveIn_RecordingStopped;
         //Формат wav-файла - принимает параметры - частоту дискретизации и количество каналов(здесь mono)
         waveIn.WaveFormat = new WaveFormat(8000, 1);
         //Инициализируем объект WaveFileWriter
         writer = new WaveFileWriter(outputFilename, waveIn.WaveFormat);
         //Начало записи
         waveIn.StartRecording();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
        /// <summary>
        /// 连接到对方设备端
        /// </summary>
        /// <param name="endPoint"></param>
        /// <param name="inputDeviceNumber"></param>
        /// <param name="codec"></param>
        private void Connect(IPEndPoint endPoint, int inputDeviceNumber, INetworkChatCodec codec)
        {
            waveIn = new WaveIn();
            waveIn.BufferMilliseconds = 50;
            waveIn.DeviceNumber       = inputDeviceNumber;
            waveIn.WaveFormat         = codec.RecordFormat;
            waveIn.DataAvailable     += waveIn_DataAvailable;
            waveIn.StartRecording();

            udpSender   = new UdpClient();
            udpListener = new UdpClient();

            // To allow us to talk to ourselves for test purposes:
            // http://stackoverflow.com/questions/687868/sending-and-receiving-udp-packets-between-two-programs-on-the-same-computer
            udpListener.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            udpListener.Client.Bind(endPoint);

            udpSender.Connect(endPoint);

            waveOut      = new WaveOut();
            waveProvider = new BufferedWaveProvider(codec.RecordFormat);
            waveOut.Init(waveProvider);
            waveOut.Play();

            connected = true;
            var state = new ListenerThreadState {
                Codec = codec, EndPoint = endPoint
            };

            ThreadPool.QueueUserWorkItem(ListenerThread, state);
        }
Esempio n. 6
0
 //старт записи
 void StartRec() // метод ввода сигнала
 {
     if (waveIn == null)
     {
         N_Input = 0;
         int sampleRate = Convert.ToInt32(toolStripComboBox1.Text); // установка
         int Bits       = Convert.ToInt32(toolStripComboBox2.Text); // параметров
         int Channels   = Convert.ToInt32(toolStripComboBox3.Text); // ввода сигнала
         dont_do_event = true;
         enabledButton(false);
         bildGraf(Channels); // настройка элемента отображения графика chart
         toolStripStatusLabel1.Text      = "Ввод сигнала запущен";
         toolStripStatusLabel1.BackColor = Color.LightCoral;
         fileName                  = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".wav";        // создание имени временного файла
         waveIn                    = new WaveIn();                                                             // подготовка устройства ввода сигнала
         waveIn.DeviceNumber       = source.InputDevice;                                                       // выбор устройства
         waveIn.DataAvailable     += waveIn_DataAvailable;                                                     // событие при котором происходит запись байтов в файл и построение графика
         waveIn.RecordingStopped  += new EventHandler <NAudio.Wave.StoppedEventArgs>(waveIn_RecordingStopped); // событие указывающее о том, что все байты получены. Необходимо для остановки записи
         waveIn.WaveFormat         = new WaveFormat(sampleRate, Bits, Channels);                               // установка параметров файла
         waveIn.BufferMilliseconds = 250;                                                                      // время записи байтов в буфер
         writer                    = new WaveFileWriter(fileName, waveIn.WaveFormat);                          // создание файла с указанием формата и пути
         waveIn.StartRecording();                                                                              // начало записи
         dont_do_event = false;
     }
 }
Esempio n. 7
0
 /// <summary>
 /// Click handler for the record button
 /// </summary>
 /// <param name="sender">The object that sent the event</param>
 /// <param name="e">Event arguments object</param>
 private void record_Click(object sender, RoutedEventArgs e)
 {
     record.IsEnabled     = false;
     stopRecord.IsEnabled = true;
     _waveIn.StartRecording();
     setStatus("Recording...");
 }
        private void btnIniciar_Click(object sender, RoutedEventArgs e)
        {
            timer.Start();

            aparecerNotaMorado(notaMorada[contadorNotaMorada]);

            if (waveOut != null)
            {
                if (waveOut.PlaybackState == PlaybackState.Playing)
                {
                    waveOut.Stop();
                }
                reader = new AudioFileReader("graficos\\Tragos.wav");
                waveOut.Init(reader);
                waveOut.Play();
            }

            wavein            = new WaveIn();
            wavein.WaveFormat = new WaveFormat(44100, 16, 1);
            formato           = wavein.WaveFormat;

            wavein.DataAvailable     += OnDataAvailable;
            wavein.BufferMilliseconds = 500;

            wavein.StartRecording();
        }
Esempio n. 9
0
 public void start()
 {
     if (waveIn != null)
     {
         waveIn.StartRecording();
     }
 }
Esempio n. 10
0
        public Form1()
        {
            InitializeComponent();

            // see what audio devices are available
            int devcount = WaveIn.DeviceCount;

            Console.Out.WriteLine("Device Count: {0}.", devcount);

            // get the WaveIn class started
            WaveIn wi = new WaveIn();

            wi.DeviceNumber = 0;
            wi.WaveFormat   = new NAudio.Wave.WaveFormat(RATE, 1);

            // create a wave buffer and start the recording
            wi.DataAvailable += new EventHandler <WaveInEventArgs>(wi_DataAvailable);
            bwp = new BufferedWaveProvider(wi.WaveFormat);
            //ISampleProvider samples=bwp.ToSampleProvider();
            bwp.BufferLength = BUFFERSIZE * 2;

            bwp.DiscardOnBufferOverflow = true;
            wi.StartRecording();;
            //waveOut = new NAudio.Wave.DirectSoundOut();
            //    waveOut.Init(samples);
            //   waveOut.Play();
        }
Esempio n. 11
0
 //Кнопка "Запись"
 private void button_rec_Click(object sender, EventArgs e)
 {
     button_stop.Enabled = true;
     timer.Start();
     ind = 1;
     try
     {
         waveIn = new WaveIn();
         waveIn.DeviceNumber      = 0;                                   //Дефолтное устройство для записи (если оно имеется)
         waveIn.DataAvailable    += waveIn_DataAvailable;                //Прикрепляем к событию DataAvailable обработчик, возникающий при наличии записываемых данных
         waveIn.RecordingStopped += waveIn_RecordingStopped;             //Прикрепляем обработчик завершения записи
         waveIn.WaveFormat        = new WaveFormat(8000, 1);             //Формат wav-файла - принимает параметры - частоту дискретизации и количество каналов(здесь mono)
         writer = new WaveFileWriter(outputFilename, waveIn.WaveFormat); //Инициализируем объект WaveFileWriter
         waveIn.StartRecording();                                        //Начало записи
         button_play.Enabled = false;
         button_rec.Enabled  = false;
         numeric.Enabled     = false;
     }
     catch (Exception ex)
     {
         button_play.Enabled = true;
         button_rec.Enabled  = true;
         numeric.Enabled     = true;
         MessageBox.Show(ex.Message);
     }
 }
Esempio n. 12
0
        void RecordNewSoundClick(object sender, EventArgs e)
        {
            if (listDevices.SelectedItems.Count == 0)
            {
                MessageBox.Show("Debe Seleccionar algun metodo de captura de la lista.");
                return;
            }

            if (nameAudio.Text.Trim() == "")
            {
                MessageBox.Show("Debe escribir un nombre para el audio.");
                return;
            }

            if (!Directory.Exists("./Sounds"))
            {
                Directory.CreateDirectory("./Sounds");
            }

            DisposeWaveRecord();

            int deviceNumber = listDevices.SelectedItems[0].Index;

            sourceStream = new WaveIn();
            sourceStream.DeviceNumber      = deviceNumber;
            sourceStream.WaveFormat        = new WaveFormat(fs, channel);
            sourceStream.DataAvailable    += sourceStream_DataAvailable;
            sourceStream.RecordingStopped += sourceStream_sStopped;
            string sfile = nameAudio.Text.Trim();

            waveWriter = new WaveFileWriter("./Sounds/" + sfile + "_raw.wav", sourceStream.WaveFormat);
            sourceStream.StartRecording();
        }
Esempio n. 13
0
        public void Init(IAudioCodec codec)
        {
            this.codec = codec;

            // Init record input
            input = new WaveIn();
            input.DeviceNumber   = cbInput.SelectedIndex;
            input.WaveFormat     = codec.RecordFormat;
            input.DataAvailable += Input_DataAvailable;
            input.StartRecording();

            // Init buffer - level meters will use it
            buffer             = new BufferedWaveProvider(codec.RecordFormat);
            InputBufferMilisec = 50;

            // Init level meters
            channel = new SampleChannel(buffer, true);
            var meter = new MeteringSampleProvider(channel);

            meter.StreamVolume += Meter_StreamVolume;

            // Init feedback output
            output        = new WaveOut();
            output.Volume = FeedbackVolume;
            output.Init(meter);
            output.Play();

            Ready = true;
        }
Esempio n. 14
0
        public void StartRecording(string filePath)
        {
            sourceStream = new WaveIn();
            sourceStream.WaveFormat = new WaveFormat(44100, WaveIn.GetCapabilities(this.InputDeviceIndex).Channels);
            sourceStream.DataAvailable += this.SourceStreamDataAvailable;
         //   sourceStream.RecordingStopped += SourceStream_RecordingStopped;
            waveWriter = new WaveFileWriter(filePath, sourceStream.WaveFormat);

            sourceStream.StartRecording();

            //sourceStream = new WaveIn
            //{
            //    DeviceNumber = this.InputDeviceIndex,
            //    WaveFormat =
            //        new WaveFormat(44100, WaveIn.GetCapabilities(this.InputDeviceIndex).Channels)
            //};

            //sourceStream.DataAvailable += this.SourceStreamDataAvailable;

            //FileInfo fi = new FileInfo(filePath);
            //if (!Directory.Exists(fi.DirectoryName))
            //{
            //    Directory.CreateDirectory(fi.DirectoryName);
            //}

            //waveWriter = new WaveFileWriter(filePath, sourceStream.WaveFormat);
            //sourceStream.StartRecording();
        }
Esempio n. 15
0
        private void Connect_button_Click(object sender, EventArgs e)
        {
            #region NAudio-staff
            waveIn = new WaveIn();
            waveIn.BufferMilliseconds = 100;
            waveIn.NumberOfBuffers    = 10;
            waveOut = new WaveOut();

            waveIn.DeviceNumber      = 0;
            waveIn.DataAvailable    += new EventHandler <WaveInEventArgs>(waveIn_DataAvailable);
            waveIn.WaveFormat        = new WaveFormat(44200, 2);
            waveIn.RecordingStopped += new EventHandler <StoppedEventArgs>(waveIn_RecordingStopped);

            sound      = new MemoryStream();
            waveWriter = new WaveFileWriter(sound, waveIn.WaveFormat);
            #endregion


            remoteAddress = reAdd.Text;
            remotePort    = Int32.Parse(rePort.Text);

            localAddress = loAdd.Text;
            localPort    = Int32.Parse(loPort.Text);

            recieve_thread = new Thread(recv);
            recieve_thread.Start();

            waveIn.StartRecording();
        }
Esempio n. 16
0
        private void initAudio()
        //private void StartBtn_Click(object sender, EventArgs e)
        {
            if (waveIn != null)
            {
                return;
            }

            // create wave input from mic
            waveIn = new WaveIn(SelectedLectureWindow.HandleWindow);
            waveIn.BufferMilliseconds = 25;
            //waveIn.RecordingStopped += waveIn_RecordingStopped;
            waveIn.DataAvailable += waveIn_DataAvailable;

            // create wave provider
            waveProvider = new BufferedWaveProvider(waveIn.WaveFormat);

            // create wave output to speakers
            waveOut = new WaveOut();
            waveOut.DesiredLatency = 100;
            waveOut.Init(waveProvider);
            //waveOut.PlaybackStopped += wavePlayer_PlaybackStopped;

            // start recording and playback
            waveIn.StartRecording();
            waveOut.Play();
        }
Esempio n. 17
0
        public string StartRecord()
        {
            var resultname = "";

            if (ON == false)
            {
                waveIn = new WaveIn();
                waveIn.DeviceNumber      = 0;
                waveIn.DataAvailable    += waveIn_DataAvailable;
                waveIn.RecordingStopped += new EventHandler <StoppedEventArgs>(waveIn_RecordingStopped);
                waveIn.WaveFormat        = new WaveFormat(16000, 1);
                writer     = new WaveFileWriter(outputFilename, waveIn.WaveFormat);
                resultname = "Стоп";
                waveIn.StartRecording();
                ON = true;
            }
            else
            {
                waveIn.StopRecording();
                ON         = false;
                resultname = "Сказать команду";
                dispatcherTimer.Start();
            }

            return(resultname);
        }
Esempio n. 18
0
        private void Form1_Load(object sender, EventArgs e)
        {
            byte[] apk, ask, bpk, bsk;
            NaClClient.CreateKeys(out apk, out ask);
            NaClClient.CreateKeys(out bpk, out bsk);

            var hasher = System.Security.Cryptography.SHA256.Create();

            _clientA = NaClClient.Create(apk, ask, bpk);
            _clientB = NaClClient.Create(bpk, bsk, apk);

            _sw = new Stopwatch();
            _sw.Start();

            _wave                    = new WaveIn(this.Handle);
            _wave.WaveFormat         = new WaveFormat(12000, 8, 1);
            _wave.BufferMilliseconds = 100;
            _wave.DataAvailable     += _wave_DataAvailable;
            _wave.StartRecording();

            _playback = new BufferedWaveProvider(_wave.WaveFormat);

            _waveOut = new WaveOut();
            _waveOut.DesiredLatency = 100;
            _waveOut.Init(_playback);
            _waveOut.Play();
        }
Esempio n. 19
0
 private void button1_Click_1(object sender, EventArgs e)
 {
     if (waveIn == null)
     {
         waveIn = new WaveIn();
         int sampleRate = 22000;
         int channels   = 2;
         waveIn.WaveFormat     = new WaveFormat(sampleRate, channels);
         waveIn.DeviceNumber   = 2;
         waveIn.DataAvailable += new EventHandler <WaveInEventArgs>(waveIn_DataAvailable);
         iii++;
         var fname = "test" + iii + ".wav";
         writer = new WaveFileWriter(fname, waveIn.WaveFormat);
         waveIn.StartRecording();
         button1.Text = "stop " + fname;
     }
     else
     {
         waveIn.StopRecording();
         waveIn.Dispose();
         writer.Close();
         waveIn       = null;
         writer       = null;
         button1.Text = "start";
     }
 }
Esempio n. 20
0
        private void btnIniciar_Click(object sender, RoutedEventArgs e)
        {
            score = 0;
            resetNubes();
            resetLeftElementos(0);
            resetLeftElementos(1);
            btnIniciar.Visibility = Visibility.Hidden;

            btnReset.Visibility = Visibility.Hidden;
            Fondo.Visibility    = Visibility.Hidden;
            lblScore.Visibility = Visibility.Hidden;

            timer.Start();
            cronometroElementos.Start();
            waveIn = new WaveIn();
            //Formato de audio
            waveIn.WaveFormat =
                new WaveFormat(44100, 16, 1);
            //Buffer
            waveIn.BufferMilliseconds =
                250;
            //¿Que hacer cuando hay muestras disponibles?
            waveIn.DataAvailable += WaveIn_DataAvailable;

            waveIn.StartRecording();


            cronometro.Start();

            bottomGlobo = (float)Canvas.GetTop(Globo);
        }
Esempio n. 21
0
        public void Start(int AudioIndex, AudioDevice device)
        {
            if (AudioIndex != -1)
            {
                input.DataAvailable += new EventHandler <WaveInEventArgs>(input_DataAvailable);
                input.DeviceNumber   = AudioIndex;

                WaveFormat format = null;

                if (device.BitRate != 0 && device.SampleRate != 0)
                {
                    format           = new WaveFormat(device.SampleRate, device.BitRate, device.Channels);
                    input.WaveFormat = format;
                }

                WaveProvider = new BufferedWaveProvider(input.WaveFormat);

                //WaveProvider.DiscardOnBufferOverflow = true;
                //make max buffer twice as long so it doesn't crash instantly and all that
                //WaveProvider.BufferLength = (int)(WaveProvider.BufferLength /5);
                WaveProvider.BufferDuration = TimeSpan.FromMilliseconds(400);
                //WaveProvider.ReadFully = false;

                volumeHandler        = new VolumeWaveProvider16(WaveProvider);
                volumeHandler.Volume = volume;

                //output.DesiredLatency = 0;
                output.Init(volumeHandler);
                output.Play();
                input.StartRecording();
                DeviceOpen = true;
            }
        }
Esempio n. 22
0
        private void BtnSendAudio_MouseDown(object sender, MouseEventArgs e)
        {
            SoundPlayer splayer = new SoundPlayer(@"Cap.wav");

            splayer.Play();

            if (!isRecording)
            {
                downTime.Start();
            }

            isRecording          = true;
            RecordingLbl.Visible = true;
            waveIn = new WaveIn(this.Handle);
            int rate           = 44100;
            int blockAlign     = (ushort)(2 * (16 / 8));
            int avgBytesPerSec = rate * blockAlign;

            waveIn.DataAvailable     += WaveIn_DataAvailable;
            waveIn.RecordingStopped  += WaveIn_RecordingStopped;
            waveIn.WaveFormat         = new WaveFormat(rate, 1);
            waveIn.BufferMilliseconds = 100;
            audioAtual = DateTime.Now.ToString("ddMMyyyy#HHmmssfff");

            string path = Path.GetPathRoot(Environment.SystemDirectory) + "\\Users\\" + Environment.UserName + "\\AppData\\Local\\Temp\\VolupiaMessenger";

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            waveFile = new WaveFileWriter(path + @"\" + _MyClient.Username + audioAtual + ".wav", waveIn.WaveFormat);

            waveIn.StartRecording();
        }
Esempio n. 23
0
 public Recorder()
 {
     waveIn = new WaveIn();
     waveIn.DataAvailable += waveIn_DataAvailable;
     waveIn.WaveFormat     = new WaveFormat(SampleRate, Channels);
     waveIn.StartRecording();
 }
Esempio n. 24
0
 private void button2_Click(object sender, EventArgs e)
 {
     if (isRec)
     {
         button2.Text = "Rec";
         if (waveIn != null)
         {
             StopRecording();
         }
     }
     else
     {
         try
         {
             waveIn = new WaveIn();
             //Дефолтное устройство для записи (если оно имеется)
             waveIn.DeviceNumber = 0;
             //Прикрепляем к событию DataAvailable обработчик, возникающий при наличии записываемых данных
             waveIn.DataAvailable += waveIn_DataAvailable;
             //Прикрепляем обработчик завершения записи
             waveIn.RecordingStopped += new EventHandler <NAudio.Wave.StoppedEventArgs>(waveIn_RecordingStopped);
             //Формат wav-файла - принимает параметры - частоту дискретизации и количество каналов(здесь mono)
             waveIn.WaveFormat = new WaveFormat(44100, 1);
             //Инициализируем объект WaveFileWriter
             writer = new WaveFileWriter(outputFilename, waveIn.WaveFormat);
             //Начало записи
             waveIn.StartRecording();
             button2.Text = "Stop";
         }
         catch (Exception ex)
         { MessageBox.Show(ex.Message); }
     }
     isRec = !isRec;
 }
Esempio n. 25
0
        /**
         * Start recording audio waveform from the built-in microphone.
         *
         * Creates a new InProgress .flac file to save the data to.
         */
        public void StartRecordingFromMicrophone()
        {
            if (isRecording)
            {
                return;
            }
            WaveFormat waveFormat = new(AUDIO_SAMPLE_RATE_HZ, AUDIO_NUM_CHANNELS);

            waveIn = new WaveIn
            {
                WaveFormat = waveFormat
            };
            if (useAudioAsr)
            {
                audioAsr = new AudioAsr(waveFormat);
            }
            if (waveIn.WaveFormat.BitsPerSample != AUDIO_BITS_PER_SAMPLE)
            {
                // TODO(#64): Handle this exception add the app level.
                throw new NotSupportedException(
                          $"Expected wave-in bits per sample to be {AUDIO_BITS_PER_SAMPLE}, " +
                          $"but got {waveIn.WaveFormat.BitsPerSample}");
            }
            waveIn.DataAvailable += new EventHandler <WaveInEventArgs>(WaveDataAvailable);
            waveIn.StartRecording();
            isRecording = true;
        }
Esempio n. 26
0
        private void startLoopback()
        {
            stopLoopback();

            int deviceNumber = cbLoopbackDevices.SelectedIndex - 1;

            if (loopbackSourceStream == null)
            {
                loopbackSourceStream = new WaveIn();
            }
            loopbackSourceStream.DeviceNumber       = deviceNumber;
            loopbackSourceStream.WaveFormat         = new WaveFormat(44100, WaveIn.GetCapabilities(deviceNumber).Channels);
            loopbackSourceStream.BufferMilliseconds = 25;
            loopbackSourceStream.NumberOfBuffers    = 5;
            loopbackSourceStream.DataAvailable     += loopbackSourceStream_DataAvailable;

            loopbackWaveProvider = new BufferedWaveProvider(loopbackSourceStream.WaveFormat);
            loopbackWaveProvider.DiscardOnBufferOverflow = true;

            if (loopbackWaveOut == null)
            {
                loopbackWaveOut = new WaveOut();
            }
            loopbackWaveOut.DeviceNumber   = cbPlaybackDevices.SelectedIndex;
            loopbackWaveOut.DesiredLatency = 125;
            loopbackWaveOut.Init(loopbackWaveProvider);

            loopbackSourceStream.StartRecording();
            loopbackWaveOut.Play();
        }
Esempio n. 27
0
        /*  Function:       MIC_Init()
         *  Parameters:     Input mic_name
         *  Description:    Set the microphone device that corresponds to the mic_name.
         */
        public Boolean MIC_Init(string mic_name)
        {
            Int32 index        = 0;
            int   MICInDevices = WaveIn.DeviceCount;

            for (int MICInDevice = 0; MICInDevice < MICInDevices; MICInDevice++)
            {
                WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(MICInDevice);
                if (deviceInfo.ProductName == mic_name)
                {
                    int    sampleRate = 8000; // 8 kHz
                    int    channels   = 1;    // mono
                    WaveIn soundIn    = new WaveIn();
                    soundIn.WaveFormat     = new WaveFormat(sampleRate, channels);
                    soundIn.DeviceNumber   = MICInDevice;
                    soundIn.DataAvailable += new EventHandler <WaveInEventArgs>(soundIn_DataAvailable);
                    soundIn.StartRecording();
                    //Console.WriteLine("[WAV]Input sampling at " + soundIn.WaveFormat.BitsPerSample);
                    IsAudioConnected = true;

                    break;
                }
                index++;
            }
            return(IsAudioConnected);
        }
Esempio n. 28
0
        private void StartBtn_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Filter           = "Wav Files Only (*.wav)|*.wav";
            saveFileDialog.InitialDirectory = ReadConf("WavFolder");
            if (saveFileDialog.ShowDialog() != true)
            {
                return;
            }

            StartBtn.IsEnabled = false;
            StopBtn.IsEnabled  = true;

            waveSource            = new WaveIn();
            waveSource.WaveFormat = new WaveFormat(44100, 1);

            waveSource.DataAvailable    += new EventHandler <WaveInEventArgs>(waveSource_DataAvailable);
            waveSource.RecordingStopped += new EventHandler <StoppedEventArgs>(waveSource_RecordingStopped);

            waveFile = new WaveFileWriter(saveFileDialog.FileName, waveSource.WaveFormat);

            waveSource.StartRecording();
            _log.Debug("Start recording in file: " + saveFileDialog.FileName);
        }
Esempio n. 29
0
        private void Btn_startmuter_Click(object sender, EventArgs e)
        {
            if (WaveIn != null)
            {
                MessageBox.Show("Muter Already started.");
                return;
            }

            if (cbox_mic.SelectedItem == null)
            {
                MessageBox.Show("Mic not selected");
                return;
            }
            else if (cbox_out.SelectedItem == null)
            {
                MessageBox.Show("Output not selected");
                return;
            }

            WaveIn = new WaveIn();
            WaveIn.DeviceNumber  = cbox_mic.SelectedIndex;
            WaveOut              = new WaveOut();
            WaveOut.DeviceNumber = cbox_out.SelectedIndex;

            BufferedWave = new BufferedWaveProvider(WaveIn.WaveFormat);
            BufferedWave.DiscardOnBufferOverflow = true;

            WaveIn.DataAvailable += WaveIn_DataAvailable;

            WaveOut.Init(BufferedWave);
            WaveIn.StartRecording();
            WaveOut.Play();

            lbl_muterenb.Text = "Muter Started";
        }
Esempio n. 30
0
        private void recButton_callback(object sender, RoutedEventArgs e)
        {
            Button clickedButton = (Button)sender;
            var    outF          = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SoundCount");

            if (cycle == 0)
            {
                Directory.CreateDirectory(outF);
            }

            cycle++;
            if (cycle % 2 == 0)
            {
                waveSource.StopRecording();
                waveFile.Close();
                send_request();
                clickedButton.Content = "Record";
            }
            else
            {
                waveSource                   = new WaveIn();
                waveSource.WaveFormat        = new WaveFormat();
                waveSource.DataAvailable    += new EventHandler <WaveInEventArgs>(waveSource_DataAvailable);
                waveSource.RecordingStopped += new EventHandler <StoppedEventArgs>(waveSource_RecordingStopped);

                waveFile = new WaveFileWriter(@"rec.wav", waveSource.WaveFormat);

                waveSource.StartRecording();

                clickedButton.Content = "Stop";
            }
        }