コード例 #1
0
ファイル: WaveFileWriter.cs プロジェクト: step4u/MiniCRM
 public static void AppendWaveFile(string filename, IWaveProvider sourceProvider)
 {
     using (var writer = new WaveFileWriter(filename, sourceProvider.WaveFormat, FileMode.Append))
     {
         long outputLength = 0;
         var buffer = new byte[sourceProvider.WaveFormat.AverageBytesPerSecond * 4];
         while (true)
         {
             int bytesRead = sourceProvider.Read(buffer, 0, buffer.Length);
             if (bytesRead == 0)
             {
                 // end of source provider
                 break;
             }
             outputLength += bytesRead;
             if (outputLength > Int32.MaxValue)
             {
                 throw new InvalidOperationException("WAV File cannot be greater than 2GB. Check that sourceProvider is not an endless stream.");
             }
             writer.Write(buffer, 0, bytesRead);
         }
     }
 }
コード例 #2
0
		/// <summary>
		/// Write the stored audio data as a WAVE file.
		/// </summary>
		public void SaveAsWav(string filePath)
		{
			// Make sure we have data.
			if (String.IsNullOrEmpty(_tempfile))
			{
				_cbWritten = 0;
				return;
			}
			if (!File.Exists(_tempfile))
			{
				_tempfile = null;
				_cbWritten = 0;
				return;
			}
			if (_cbWritten == 0)
			{
				File.Delete(_tempfile);
				_tempfile = null;
				return;
			}
			FileInfo fi = new FileInfo(_tempfile);
			Debug.Assert(fi.Length == _cbWritten);
			WaveFileWriter writer = new WaveFileWriter(filePath);
			writer.WriteFileHeader((int)fi.Length);
			WaveFormatChunk format = new WaveFormatChunk();
			format.chunkId = "fmt ";
			format.chunkSize = 16;				// size of the struct in bytes - 8
			format.audioFormat = WAV_FMT_PCM;
			format.channelCount = _channelCount;
			format.sampleRate = _sampleRate;
			format.byteRate = (uint)(_sampleRate * _channelCount * _bitsPerFrame / 8);
			format.blockAlign = (ushort)(_channelCount * _bitsPerFrame / 8);
			format.bitsPerSample = _bitsPerFrame;
			writer.WriteFormatChunk(format);
			writer.WriteDataHeader((int)fi.Length);
			byte[] data = File.ReadAllBytes(_tempfile);
			Debug.Assert(data.Length == _cbWritten);
			writer.WriteData(data);
			writer.Close();
			// Clean up the temporary data from the recording process.
			File.Delete(_tempfile);
			_tempfile = null;
			_cbWritten = 0;
		}
コード例 #3
0
 public void WriteSamplesToWaveFile(string pathToFile, float[] samples, int sampleRate)
 {
     using (var writer = new WaveFileWriter(pathToFile, WaveFormat.CreateIeeeFloatWaveFormat(sampleRate, 1)))
     {
         writer.WriteSamples(samples, 0, samples.Length);
     }
 }
コード例 #4
0
 override public void Init(IWaveProvider w_in)
 {
     writer = new WaveFileWriter(filename, w_in.WaveFormat);
     wavein = w_in;
 }
コード例 #5
0
ファイル: MainWindow.xaml.cs プロジェクト: xiaoxiongnpu/mkd
        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            if (name != "英文" && CheckBox_Library.IsChecked == true)
            {
                MessageBox.Show("The selected language cannot use the library service.\nPlease unselect the Lib box.", "Library error");
                return;
            }

            InitializeComponent();
            this.Topmost = true;

            click            = true;
            this.WindowState = WindowState.Minimized;

            if (name == "英文" && nameTo == "英文" || name == "西班牙语" && nameTo == "西班牙语")
            {
                feedback.txtBlock.TextAlignment   = TextAlignment.Left;
                feedback.txtContent.TextAlignment = TextAlignment.Left;
            }
            else
            {
                feedback.txtBlock.TextAlignment   = TextAlignment.Center;
                feedback.txtContent.TextAlignment = TextAlignment.Center;
            }

            if (!file)
            {
                string micName = WaveIn.GetCapabilities(combDevice.SelectedIndex).ProductName;

                totalBufferLength = 0;
                recorder          = new AudioRecorder();
                if (!micName.StartsWith("Microphone"))
                {
                    recorder.RecordingFormat = new WaveFormat(8000, 2);                                    //External mics work fine. Laptop mic works soso.
                }
                recorder.MicrophoneLevel = 100;
                recorder.BeginMonitoring(combDevice.SelectedIndex);
                recorder.SampleAggregator.MaximumCalculated += OnRecorderMaximumCalculated;

                if (waveIn == null)
                {
                    waveIn = CreateWaveInDevice(micName);
                }
                var device = (MMDevice)combDevice.SelectedItem;
                device.AudioEndpointVolume.Mute = false;

                if (micName.StartsWith("Microphone"))
                {
                    waveIn.WaveFormat = new WaveFormat(16000, 1);                                   //Laptop mic works great. External mics don't work.
                }
                else
                {
                    waveIn.WaveFormat = new WaveFormat(8000, 2);  //External mics work fine. Laptop mic works soso.
                }
                if (name == "中文")
                {
                    // Start receive and send loops
                    var sendAudioRecorded = Task.Run(() => this.StartSending())
                                            .ContinueWith((t) => ReportError(t))
                                            .ConfigureAwait(false);
                }
                else if (name == "英文" || name == "西班牙语")
                {
                    stopbutton = false;
                    if (this.micClient == null)
                    {
                        this.CreateMicrophoneRecoClient();
                    }
                    this.micClient.StartMicAndRecognition();
                }

                if (CheckBox_RecordAudio.IsChecked == true && logAudioFileName != null)
                {
                    // Setup player and recorder but don't start them yet.
                    WaveFormat waveFormat;
                    if (micName.StartsWith("Microphone"))
                    {
                        waveFormat = new WaveFormat(16000, 1);                                   //Laptop mic works great. External mics don't work.
                    }
                    else
                    {
                        waveFormat = new WaveFormat(8000, 2);  //External mics work fine. Laptop mic works soso.
                    }
                    audioSent = new WaveFileWriter(logAudioFileName, waveFormat);
                    Debug.WriteLine("I: Recording outgoing audio in " + logAudioFileName);
                }
                else
                {
                    CheckBox_RecordAudio.IsEnabled = false;
                }

                waveIn.StartRecording();
            }
            else if (file)
            {
                if (name == "英文" || name == "西班牙语")
                {
                    if (null == this.dataClient)
                    {
                        this.CreateDataRecoClient();
                    }
                    this.SendAudioHelper(this.LongWaveFile);
                }
            }

            btnStart.IsEnabled = false;
            btnStop.IsEnabled  = true;

            if (CheckBox_RecordAudio.IsChecked == false)
            {
                CheckBox_RecordAudio.IsEnabled = false;
            }

            CheckBox_Transcript.IsEnabled = false;
            CheckBox_Transcript.IsChecked = false;

            CheckBox_Library.IsEnabled = false;
        }
コード例 #6
0
        private void StartButton_Click(object sender, EventArgs e)
        {
            StartButton.Enabled = false;
            StopButton.Enabled  = true;
            stopwatch.Start();

            //-------------------SystemSoundRecord---------------------------

            var dialog = new SaveFileDialog();

            dialog.Filter = "Wave files | *.wav";

            if (dialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            outputFileNameSounds = dialog.FileName;

            capture = new WasapiLoopbackCapture();
            var writer = new WaveFileWriter(outputFileNameSounds, capture.WaveFormat);

            capture.DataAvailable += async(s, ee) =>
            {
                if (writer != null)
                {
                    await writer.WriteAsync(ee.Buffer, 0, ee.BytesRecorded);

                    await writer.FlushAsync();
                }
            };

            capture.RecordingStopped += (s, ee) =>
            {
                if (writer != null)
                {
                    writer.Dispose();
                    writer = null;
                }

                StartButton.Enabled = true;
                capture.Dispose();
            };

            capture.StartRecording();

            //------------------MicRecord----------------------------------

            var micFileDialog = new SaveFileDialog();

            micFileDialog.Filter = "Wave files | *.wav";

            if (micFileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            outputFileNameMic = micFileDialog.FileName;

            wave                   = new WaveIn();
            wave.WaveFormat        = new WaveFormat(8000, 1); //44100, 1
            wave.DeviceNumber      = InputDeviceCombo.SelectedIndex;
            wave.DataAvailable    += Wave_DataAvailable;
            wave.RecordingStopped += Wave_RecordingStopped;
            writerMic              = new WaveFileWriter(outputFileNameMic, wave.WaveFormat);
            wave.StartRecording();
        }