Beispiel #1
0
        private void WriteToFile(byte[] buffer, int bytesRecorded)
        {
            long maxFileLength = this.recordingFormat.AverageBytesPerSecond * 60;

            if (recordingState == RecordingState.Recording ||
                recordingState == RecordingState.RequestedStop)
            {
                int toWrite = (int)Math.Min(maxFileLength - writer.Length, bytesRecorded);
                if (toWrite > 0)
                {
                    writer.WriteData(buffer, 0, bytesRecorded);
                }
                else
                {
                    Stop();
                }
            }
        }
 private static void TrimWavFile(WaveFileReader reader, WaveFileWriter writer, int startPos, int endPos)
 {
     reader.Position = startPos;
     byte[] buffer = new byte[1024];
     while (reader.Position < endPos)
     {
         int bytesRequired = (int)(endPos - reader.Position);
         if (bytesRequired > 0)
         {
             int bytesToRead = Math.Min(bytesRequired, buffer.Length);
             int bytesRead   = reader.Read(buffer, 0, bytesToRead);
             if (bytesRead > 0)
             {
                 writer.WriteData(buffer, 0, bytesRead);
             }
         }
     }
 }
Beispiel #3
0
        void captureDevice_DataAvailable(object sender, WaveInEventArgs e)
        {
            if (!IsRecording)
            {
                return;
            }

            byte[] buffer = e.Buffer;
            _writer.WriteData(buffer, 0, e.BytesRecorded);

            if (OnSample != null)
            {
                for (int index = 0; index < e.BytesRecorded; index += 2)
                {
                    short sample   = (short)((buffer[index + 1] << 8) | buffer[index + 0]);
                    float sample32 = sample / 32768f;
                    OnSample(this, new SampleEventArgs(sample32, 0));
                }
            }
        }
Beispiel #4
0
 void waveIn_DataAvailable(object sender, WaveInEventArgs e)
 {
     if (this.InvokeRequired)
     {
         //Debug.WriteLine("Data Available");
         this.BeginInvoke(new EventHandler <WaveInEventArgs>(waveIn_DataAvailable), sender, e);
     }
     else
     {
         //Debug.WriteLine("Flushing Data Available");
         writer.WriteData(e.Buffer, 0, e.BytesRecorded);
         int secondsRecorded = (int)(writer.Length / writer.WaveFormat.AverageBytesPerSecond);
         if (secondsRecorded >= 30)
         {
             StopRecording();
         }
         else
         {
             progressBar1.Value = secondsRecorded;
         }
     }
 }
Beispiel #5
0
 //получение данных из входного буфера для распознавания
 void waveIn_DataAvailable(object sender, WaveInEventArgs e)
 {
     if (this.InvokeRequired)
     {
         this.BeginInvoke(new EventHandler <WaveInEventArgs>(waveIn_DataAvailable), sender, e);
     }
     else
     {
         //переменная для обозначения начала распознавания речевого отрезка
         bool result = ProcessData(e);
         // Если записываемый отрезок содержит речь
         if (result == true)
         {
             //Записываем данные из буфера в файл
             writer.WriteData(e.Buffer, 0, e.BytesRecorded);
         }
         else
         {
             // если речь не определена на звуковом отрезке
         }
     }
 }
Beispiel #6
0
 public static void ApplyAutoTune(string fileToProcess, string tempFile, AutoTuneSettings autotuneSettings)
 {
     using (WaveFileReader reader = new WaveFileReader(fileToProcess))
     {
         IWaveProvider stream32     = new Wave16ToFloatProvider(reader);
         IWaveProvider streamEffect = new AutoTuneWaveProvider(stream32, autotuneSettings);
         IWaveProvider stream16     = new WaveFloatTo16Provider(streamEffect);
         using (WaveFileWriter converted = new WaveFileWriter(tempFile, stream16.WaveFormat))
         {
             // buffer length needs to be a power of 2 for FFT to work nicely
             // however, make the buffer too long and pitches aren't detected fast enough
             // successful buffer sizes: 8192, 4096, 2048, 1024
             // (some pitch detection algorithms need at least 2048)
             byte[] buffer = new byte[8192];
             int    bytesRead;
             do
             {
                 bytesRead = stream16.Read(buffer, 0, buffer.Length);
                 converted.WriteData(buffer, 0, bytesRead);
             } while (bytesRead != 0 && converted.Length < reader.Length);
         }
     }
 }
        private void SplitWav(TimeSpan start, TimeSpan end, String input, String output)
        {
            using (WaveFileReader reader = new WaveFileReader(input))
            {
                using (WaveFileWriter writer = new WaveFileWriter(output, reader.WaveFormat))
                {
                    int segement = reader.WaveFormat.AverageBytesPerSecond / 1000;

                    int startPosition = (int)start.TotalMilliseconds * segement;
                    startPosition = startPosition - startPosition % reader.WaveFormat.BlockAlign;

                    int endBytes = (int)end.TotalMilliseconds * segement;
                    endBytes = endBytes - endBytes % reader.WaveFormat.BlockAlign;
                    int endPosition = (int)reader.Length - endBytes;


                    reader.Position = startPosition;
                    byte[] buffer = new byte[1024];
                    while (reader.Position < endPosition)
                    {
                        int segment = (int)(endPosition - reader.Position);
                        if (segment > 0)
                        {
                            int bytesToRead = Math.Min(segment, buffer.Length);
                            int bytesRead   = reader.Read(buffer, 0, bytesToRead);
                            if (bytesRead > 0)
                            {
#pragma warning disable CS0618 // Type or member is obsolete
                                writer.WriteData(buffer, 0, bytesRead);
#pragma warning restore CS0618 // Type or member is obsolete
                            }
                        }
                    }
                }
            }
        }
Beispiel #8
0
 void waveIn_DataAvailable(object sender, WaveInEventArgs e1)
 {
     writer.WriteData(e1.Buffer, 0, e1.BytesRecorded);
 }
Beispiel #9
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;
		}
Beispiel #10
0
 static void waveSource_DataAvailable(object sender, WaveInEventArgs e)
 {
     waveFile.WriteData(e.Buffer, 0, e.BytesRecorded);
 }
Beispiel #11
0
 void waveIn_DataAvailable(object sender, WaveInEventArgs e)
 {
     waveFileWriter.WriteData(e.Buffer, 0, e.BytesRecorded);
     waveFileWriter.Flush();
 }
Beispiel #12
0
 private void waveInStream_DataAvailable(object sender, WaveInEventArgs e)
 {
     writer.WriteData(e.Buffer, 0, e.BytesRecorded);
     int secondsRecorded = (int)(writer.Length / writer.WaveFormat.AverageBytesPerSecond);
 }
Beispiel #13
0
        /// <exception cref="NotImplementedException">NOT IMPLEMENTED !</exception>
        public string UnCompressMp3File(string sourceFile, string destinationDirectory, int destChannels, int destSamplingRate, int destBitDepth)
        {
            if (!File.Exists(sourceFile))
            {
                throw new FileNotFoundException("Invalid source file path");
            }

            if (!Directory.Exists(destinationDirectory))
            {
                throw new FileNotFoundException("Invalid destination directory");
            }

            string destinationFilePath = null;
            //PCMFormatInfo pcmFormat = null;
            int channels   = 0;
            int sampleRate = 0;
            int bitDepth   = 0;

            /*
             * bool exceptionError = false;
             * using (Mp3FileReader mp3Reader = new Mp3FileReader(sourceFile))
             * {
             *  using (WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream(mp3Reader))
             *  {
             *      //pcmFormat = new PCMFormatInfo((ushort)pcmStream.WaveFormat.Channels,
             *                                              //(uint)pcmStream.WaveFormat.SampleRate,
             *                                              //(ushort)pcmStream.WaveFormat.BitsPerSample);
             *  channels = pcmStream.WaveFormat.Channels;
             *  sampleRate = pcmStream.WaveFormat.SampleRate;
             *  bitDepth = pcmStream.WaveFormat.BitsPerSample;
             *      destinationFilePath = GenerateOutputFileFullname ( sourceFile + ".wav", destinationDirectory, pcmStream.WaveFormat.Channels, pcmStream.WaveFormat.SampleRate, pcmStream.WaveFormat.BitsPerSample );
             *      using (WaveFileWriter writer = new WaveFileWriter(destinationFilePath, pcmStream.WaveFormat))
             *      {
             *          const int BUFFER_SIZE = 1024 * 8; // 8 KB MAX BUFFER
             *          byte[] buffer = new byte[BUFFER_SIZE];
             *          int byteRead;
             *          try
             *          {
             *              writer.Flush();
             *              while ((byteRead = pcmStream.Read(buffer, 0, buffer.Length)) > 0)
             *              {
             *                  writer.WriteData(buffer, 0, byteRead);
             *              }
             *          }
             *          catch (Exception ex)
             *          {
             *              pcmStream.Close();
             *              writer.Close();
             *              //pcmFormat = null;
             *              exceptionError = true;
             *          }
             *      }
             *  }
             * }
             *
             * //if (pcmFormat == null)
             * if ( exceptionError )
             * {
             *  // in case of exception, delete incomplete file just created
             * if (File.Exists ( destinationFilePath ))
             *  {
             *  File.Delete ( destinationFilePath );
             *  }
             */
            Stream fileStream = File.Open(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read);

            if (fileStream != null)
            {
                int totalBytesWritten = 0;
                using (NLayerMp3Stream mp3Stream = new NLayerMp3Stream(fileStream))
                {
                    //pcmFormat = new PCMFormatInfo((ushort)mp3Stream.WaveFormat.Channels,
                    //(uint)mp3Stream.WaveFormat.SampleRate,
                    //(ushort)mp3Stream.WaveFormat.BitsPerSample);
                    channels            = mp3Stream.WaveFormat.Channels;
                    sampleRate          = mp3Stream.WaveFormat.SampleRate;
                    bitDepth            = mp3Stream.WaveFormat.BitsPerSample;
                    destinationFilePath = GenerateOutputFileFullname(sourceFile + ".wav", destinationDirectory, mp3Stream.WaveFormat.Channels, mp3Stream.WaveFormat.SampleRate, mp3Stream.WaveFormat.BitsPerSample);
                    using (WaveFileWriter writer = new WaveFileWriter(destinationFilePath, mp3Stream.WaveFormat))
                    {
                        int buffSize = mp3Stream.GetReadSize(4000);
                        //const int BUFFER_SIZE = 1024 * 8; // 8 KB MAX BUFFER
                        byte[] buffer = new byte[buffSize];
                        try
                        {
                            int byteRead;
                            writer.Flush();
                            while ((byteRead = mp3Stream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                Console.WriteLine("memory is " + (System.GC.GetTotalMemory(false) / 1024).ToString());
                                writer.WriteData(buffer, 0, byteRead);
                                totalBytesWritten += byteRead;
                            }
                        }
                        catch (Exception ex)
                        {
                            writer.Close();
                            System.Windows.Forms.MessageBox.Show(ex.ToString());
                            return(null);
                        }
                    }
                }
                if (totalBytesWritten == 0)
                {
                    return(null);
                }
            }
            else
            {
                return(null);
            }
            //}

            //if (!pcmFormat.IsCompatibleWith(destinationPCMFormat))
            if (channels != destChannels ||
                sampleRate != destSamplingRate ||
                bitDepth != destBitDepth)
            {
                string newDestinationFilePath = ConvertSampleRate(destinationFilePath, destinationDirectory, destChannels, destSamplingRate, destBitDepth);
                if (File.Exists(destinationFilePath))
                {
                    File.Delete(destinationFilePath);
                }
                return(newDestinationFilePath);
            }
            return(destinationFilePath);
        }
Beispiel #14
0
        static void Main(string[] args)
        {
            Console.WriteLine("nub2wav");
            Console.WriteLine("Created by nzgamer41");

            if (args.Length < 1)
            {
                Console.WriteLine("Usage: nub2wav.exe <path to nub file> <optional bitrate>");
            }
            else
            {
                try
                {
                    int bitrate = 44100;
                    if (args.Length == 2)
                    {
                        bitrate = int.Parse(args[1]);
                        Console.WriteLine("Bitrate is set to: " + bitrate);
                    }

                    //automatic bitrate detection, but only if custom bitrate isn't supplied
                    if (args.Length != 2)
                    {
                        String fileName = Path.GetFileName(args[0]);
                        Console.WriteLine("Checking bitrate...");

                        if (bitRate44100.Contains(fileName))
                        {
                            bitrate = 44100;
                            Console.WriteLine("Bitrate is set to: " + bitrate);
                        }
                        else if (bitRate32000.Contains(fileName))
                        {
                            bitrate = 32000;
                            Console.WriteLine("Bitrate is set to: " + bitrate);
                        }
                        else
                        {
                            Console.WriteLine(fileName + " is unrecognized, defaulting to " + bitrate);
                        }
                    }


                    var    path = args[0];
                    byte[] file = File.ReadAllBytes(path);
                    //hopefully should convert big endian to little endian for converting to wav
                    Array.Reverse(file);

                    var s          = new RawSourceWaveStream(new MemoryStream(file), new WaveFormat(bitrate, 16, 2));
                    var outpath    = Path.ChangeExtension(path, ".wav");
                    int blockAlign = s.WaveFormat.BlockAlign;
                    using (WaveFileWriter writer = new WaveFileWriter(outpath, s.WaveFormat))
                    {
                        byte[] buffer  = new byte[blockAlign];
                        long   samples = s.Length / blockAlign;
                        for (long sample = samples - 1; sample >= 0; sample--)
                        {
                            s.Position = sample * blockAlign;
                            s.Read(buffer, 0, blockAlign);
                            writer.WriteData(buffer, 0, blockAlign);
                        }
                    }
                    Console.WriteLine(args[0] + " converted to " + outpath);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
Beispiel #15
0
 void wi_DataAvailable(object sender, WaveInEventArgs e)
 {
     writer.WriteData(e.Buffer, 0, e.BytesRecorded);
     ssound_feed(m_engine, e.Buffer, e.Buffer.Length);
 }
Beispiel #16
0
        /// <summary>
        /// Load wave file and change its tempo, pitch and rate and save it to another file
        /// </summary>
        static void processWave(string fileIn, string fileOut, float newTempo, float newPitch, float newRate)
        {
            WaveFileReader reader      = new WaveFileReader(fileIn);
            int            numChannels = reader.WaveFormat.Channels;

            if (numChannels > 2)
            {
                throw new Exception("SoundTouch supports only mono or stereo.");
            }
            int            sampleRate   = reader.WaveFormat.SampleRate;
            int            bitPerSample = reader.WaveFormat.BitsPerSample;
            const int      BUFFER_SIZE  = 1024 * 16;
            SoundStretcher stretcher    = new SoundStretcher(sampleRate, numChannels);
            WaveFileWriter writer       = new WaveFileWriter(fileOut, new WaveFormat(sampleRate, 16, numChannels));

            stretcher.Tempo = newTempo;
            stretcher.Pitch = newPitch;
            stretcher.Rate  = newRate;
            byte[]  buffer  = new byte[BUFFER_SIZE];
            short[] buffer2 = null;

            if (bitPerSample != 16 && bitPerSample != 8)
            {
                throw new Exception("Not implemented yet.");
            }

            if (bitPerSample == 8)
            {
                buffer2 = new short[BUFFER_SIZE];
            }

            bool finished = false;

            while (true)
            {
                int bytesRead = 0;
                if (!finished)
                {
                    bytesRead = reader.Read(buffer, 0, BUFFER_SIZE);
                    if (bytesRead == 0)
                    {
                        finished = true;
                        stretcher.Flush();
                    }
                    else
                    {
                        if (bitPerSample == 16)
                        {
                            stretcher.PutSamplesFromBuffer(buffer, 0, bytesRead);
                        }
                        else if (bitPerSample == 8)
                        {
                            for (int i = 0; i < BUFFER_SIZE; i++)
                            {
                                buffer2[i] = (short)((buffer[i] - 128) * 256);
                            }
                            stretcher.PutSamples(buffer2);
                        }
                    }
                }

                bytesRead = stretcher.ReceiveSamplesToBuffer(buffer, 0, BUFFER_SIZE);
                writer.WriteData(buffer, 0, bytesRead);
                if (finished && bytesRead == 0)
                {
                    break;
                }
            }

            reader.Close();
            writer.Close();
        }
Beispiel #17
0
 void WaveInDataAvailable(object sender, WaveInEventArgs e)
 {
     writer.WriteData(e.Buffer, 0, e.BytesRecorded);
 }