/// <summary> /// Read an audio file. /// </summary> void Read() { reader = new MediaFoundationReader(fileName); duration = reader.TotalTime; format = new AudioFormat(reader.WaveFormat); var bytes = new byte[reader.Length]; var read = reader.Read(bytes, 0, bytes.Length); data = new List<byte>(bytes); }
/// <summary> /// Reads bytes from this stream /// </summary> /// <param name="array">Buffer to read into</param> /// <param name="offset">Offset in array to read into</param> /// <param name="count">Number of bytes to read</param> /// <returns>Number of bytes read</returns> public override int Read(byte[] array, int offset, int count) { lock (lockObject) { if (Enabled) { if (sourceBuffer == null || sourceBuffer.Length < count) { sourceBuffer = new byte[count]; } int sourceBytesRead = sourceStream.Read(sourceBuffer, 0, count); int sampleCount = sourceBytesRead / (bytesPerSample * channels); for (int sample = 0; sample < sampleCount; sample++) { int start = sample * bytesPerSample * channels; double in1; double in2; ReadSamples(sourceBuffer, start, out in1, out in2); simpleCompressor.Process(ref in1, ref in2); WriteSamples(array, offset + start, in1, in2); } return(count); } else { return(sourceStream.Read(array, offset, count)); } } }
/// <summary> /// Reads bytes from this wave stream /// </summary> /// <param name="destBuffer">The destination buffer</param> /// <param name="offset">Offset into the destination buffer</param> /// <param name="numBytes">Number of bytes read</param> /// <returns>Number of bytes read.</returns> public override int Read(byte[] destBuffer, int offset, int numBytes) { int bytesWritten = 0; // 1. fill with silence if (position < audioStartPosition) { bytesWritten = (int)Math.Min(numBytes, audioStartPosition - position); for (int n = 0; n < bytesWritten; n++) { destBuffer[n + offset] = 0; } } if (bytesWritten < numBytes) { // don't read too far into source stream int sourceBytesRequired = (int)Math.Min( numBytes - bytesWritten, sourceLengthBytes + sourceOffsetBytes - sourceStream.Position); int read = sourceStream.Read(destBuffer, bytesWritten + offset, sourceBytesRequired); bytesWritten += read; } // 3. Fill out with zeroes for (int n = bytesWritten; n < numBytes; n++) { destBuffer[offset + n] = 0; } position += numBytes; return(numBytes); }
/// <summary> /// Reads bytes from this wave stream /// </summary> /// <param name="destBuffer">Destination buffer</param> /// <param name="offset">Offset into destination buffer</param> /// <param name="numBytes"></param> /// <returns>Number of bytes read.</returns> public override int Read(byte[] destBuffer, int offset, int numBytes) { byte[] sourceBuffer = new byte[numBytes * 2]; int bytesRead = sourceStream.Read(sourceBuffer, 0, numBytes * 2); Convert32To16(destBuffer, offset, sourceBuffer, bytesRead); position += (bytesRead / 2); return(bytesRead / 2); }
/// <summary> /// Reads bytes from this wave stream /// </summary> /// <param name="destBuffer">The destination buffer</param> /// <param name="offset">Offset into the destination buffer</param> /// <param name="numBytes">Number of bytes read</param> /// <returns>Number of bytes read.</returns> public override int Read(byte[] destBuffer, int offset, int numBytes) { int bytesWritten = 0; // 1. fill with silence if (position < 0) { bytesWritten = (int)Math.Min(numBytes, 0 - position); for (int n = 0; n < bytesWritten; n++) { destBuffer[n + offset] = 0; } } if (bytesWritten < numBytes) { if (sourceStream.WaveFormat.Channels == 1) { int sourceBytesRequired = (numBytes - bytesWritten) / 4; byte[] sourceBuffer = GetSourceBuffer(sourceBytesRequired); int read = sourceStream.Read(sourceBuffer, 0, sourceBytesRequired); MonoToStereo(destBuffer, offset + bytesWritten, sourceBuffer, read); bytesWritten += (read * 4); } else { int sourceBytesRequired = (numBytes - bytesWritten) / 2; byte[] sourceBuffer = GetSourceBuffer(sourceBytesRequired); int read = sourceStream.Read(sourceBuffer, 0, sourceBytesRequired); AdjustVolume(destBuffer, offset + bytesWritten, sourceBuffer, read); bytesWritten += (read * 2); } } // 3. Fill out with zeroes if (PadWithZeroes && bytesWritten < numBytes) { Array.Clear(destBuffer, offset + bytesWritten, numBytes - bytesWritten); bytesWritten = numBytes; } position += bytesWritten; return(bytesWritten); }
private static void Extract(Stream output, WaveStream waveStream, byte[] buffer) { if (waveStream == null) return; using (WaveFileWriter writer = new WaveFileWriter(output, waveStream.WaveFormat)) { int count; while ((count = waveStream.Read(buffer, 0, buffer.Length)) != 0) writer.Write(buffer, 0, count); } }
/// <summary> /// Reads bytes from this wave stream /// </summary> /// <param name="destBuffer">Destination buffer</param> /// <param name="offset">Offset into destination buffer</param> /// <param name="numBytes"></param> /// <returns>Number of bytes read.</returns> public override int Read(byte[] destBuffer, int offset, int numBytes) { lock (lockObject) { int count = numBytes * 2; sourceBuffer = BufferHelpers.Ensure(sourceBuffer, count); int bytesRead = sourceStream.Read(sourceBuffer, 0, count); Convert32To16(destBuffer, offset, sourceBuffer, bytesRead); position += (bytesRead / 2); return(bytesRead / 2); } }
/// <summary> /// Creates a Wave file by reading all the data from a WaveStream /// </summary> /// <param name="filename">The filename to use</param> /// <param name="stream">The source WaveStream</param> public static void CreateWaveFile(string filename, WaveStream stream) { using (WaveFileWriter writer = new WaveFileWriter(filename, stream.WaveFormat)) { byte[] buffer = new byte[stream.GetReadSize(4000)]; while (true) { int bytesRead = stream.Read(buffer, 0, buffer.Length); if (bytesRead == 0) break; writer.WriteData(buffer, 0, bytesRead); } } }
/// <summary> /// Reads data from input stream /// </summary> /// <param name="buffer">buffer</param> /// <param name="offset">offset into buffer</param> /// <param name="count">Bytes required</param> /// <returns>Number of bytes read</returns> public override int Read(byte[] buffer, int offset, int count) { int outputBytesProvided = 0; while (outputBytesProvided < count) { if (resampler.MediaObject.IsAcceptingData(0)) { // 1. Read from the input stream int inputBytesRequired = (int)OutputToInputPosition(count - outputBytesProvided); byte[] inputByteArray = new byte[inputBytesRequired]; int inputBytesRead = inputStream.Read(inputByteArray, 0, inputBytesRequired); if (inputBytesRead == 0) { Debug.WriteLine("ResamplerDmoStream.Read: No input data available"); break; } // 2. copy into our DMO's input buffer inputMediaBuffer.LoadData(inputByteArray, inputBytesRead); // 3. Give the input buffer to the DMO to process resampler.MediaObject.ProcessInput(0, inputMediaBuffer, DmoInputDataBufferFlags.None, 0, 0); outputBuffer.MediaBuffer.SetLength(0); outputBuffer.StatusFlags = DmoOutputDataBufferFlags.None; // 4. Now ask the DMO for some output data resampler.MediaObject.ProcessOutput(DmoProcessOutputFlags.None, 1, new DmoOutputDataBuffer[] { outputBuffer }); if (outputBuffer.Length == 0) { Debug.WriteLine("ResamplerDmoStream.Read: No output data available"); break; } // 5. Now get the data out of the output buffer outputBuffer.RetrieveData(buffer, offset + outputBytesProvided); outputBytesProvided += outputBuffer.Length; Debug.Assert(!outputBuffer.MoreDataAvailable, "have not implemented more data available yet"); } else { Debug.Assert(false, "have not implemented not accepting logic yet"); } } position += outputBytesProvided; return(outputBytesProvided); }
/// <summary> /// Creates a Wave file by reading all the data from a WaveStream /// </summary> /// <param name="filename">The filename to use</param> /// <param name="stream">The source WaveStream</param> public static void CreateWaveFile(string filename, WaveStream stream) { using (WaveFileWriter writer = new WaveFileWriter(filename, stream.WaveFormat)) { byte[] buffer = new byte[stream.GetReadSize(4000)]; while (true) { int bytesRead = stream.Read(buffer, 0, buffer.Length); if (bytesRead == 0) { break; } writer.WriteData(buffer, 0, bytesRead); } } }
static void Main(string[] args) { var A = generateSound(440, 48000, 5); var waveFormat = new WaveFormat(8000, 16, 1); using (WaveFileWriter writer = new WaveFileWriter("OLOLO.wav", waveFormat)) { writer.WriteData(A, 0, A.Length); } return; NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.WaveFileReader(WavFilePath)); if (pcm.WaveFormat.Channels != 2) { return; } int someInterval = pcm.WaveFormat.Channels * pcm.WaveFormat.SampleRate * pcm.WaveFormat.BitsPerSample / 8; float time = 10; // 10 secs float samplingRate = pcm.WaveFormat.SampleRate; int index = (int)(time / samplingRate); byte[] buffer = new byte[someInterval]; int current = 0; int ret = 0; do { ret = pcm.Read(buffer, current, someInterval); float[] res = new float[buffer.Length / 2]; for (int i = 0; i < res.Length; i += 2) { res[i] = (buffer[i] + buffer[i + 1]) / 2 / 32768.0f; } current += someInterval; } while (ret != -1); PlayPCM(pcm); }
public static void CreateAiffFile(string filename, WaveStream sourceProvider) { using (AiffFileWriter aiffFileWriter = new AiffFileWriter(filename, sourceProvider.WaveFormat)) { byte[] array = new byte[16384]; while (sourceProvider.Position < sourceProvider.Length) { int count = Math.Min((int)(sourceProvider.Length - sourceProvider.Position), array.Length); int num = sourceProvider.Read(array, 0, count); if (num == 0) { break; } aiffFileWriter.Write(array, 0, num); } } }
/// <summary> /// Creates an Aiff file by reading all the data from a WaveProvider /// BEWARE: the WaveProvider MUST return 0 from its Read method when it is finished, /// or the Aiff File will grow indefinitely. /// </summary> /// <param name="filename">The filename to use</param> /// <param name="sourceProvider">The source WaveProvider</param> public static void CreateAiffFile(string filename, WaveStream sourceProvider) { using (var writer = new AiffFileWriter(filename, sourceProvider.WaveFormat)) { byte[] buffer = new byte[16384]; while (sourceProvider.Position < sourceProvider.Length) { int count = Math.Min((int)(sourceProvider.Length - sourceProvider.Position), buffer.Length); int bytesRead = sourceProvider.Read(buffer, 0, count); if (bytesRead == 0) { // end of source provider break; } writer.Write(buffer, 0, bytesRead); } } }
/// <summary> /// Creates an Aiff file by reading all the data from a WaveProvider /// BEWARE: the WaveProvider MUST return 0 from its Read method when it is finished, /// or the Aiff File will grow indefinitely. /// </summary> /// <param name="filename">The filename to use</param> /// <param name="sourceProvider">The source WaveProvider</param> public static void CreateAiffFile(string filename, WaveStream sourceProvider) { using (var writer = new AiffFileWriter(filename, sourceProvider.WaveFormat)) { byte[] buffer = new byte[16384]; while (sourceProvider.Position < sourceProvider.Length) { int count = Math.Min((int)(sourceProvider.Length - sourceProvider.Position), buffer.Length); int bytesRead = sourceProvider.Read(buffer, 0, count); if (bytesRead == 0) { // end of source provider break; } writer.Write(buffer, 0, bytesRead); } } }
/// <summary> /// Reads data from this stream /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> /// <returns></returns> public override int Read(byte[] buffer, int offset, int count) { lock (this) { // 1. attempt to fill the circular buffer with enough data to meet our request while (BufferEndPosition < position + count) { int sourceReadCount = count; if (sourceReadCount % sourceStream.BlockAlign != 0) { sourceReadCount = (count + sourceStream.BlockAlign) - (count % sourceStream.BlockAlign); } int sourceRead = sourceStream.Read(GetSourceBuffer(sourceReadCount), 0, sourceReadCount); circularBuffer.Write(GetSourceBuffer(sourceReadCount), 0, sourceRead); if (sourceRead == 0) { // assume we have run out of data break; } } // 2. discard any unnecessary stuff from the start if (bufferStartPosition < position) { circularBuffer.Advance((int)(position - bufferStartPosition)); bufferStartPosition = position; } // 3. now whatever is in the buffer we can return int bytesRead = circularBuffer.Read(buffer, offset, count); position += bytesRead; // anything left in buffer is at start position bufferStartPosition = position; return(bytesRead); } }
/// <summary> /// Read an audio file. /// </summary> void Read() { #if WINDOWS reader = new MediaFoundationReader(fileName); duration = reader.TotalTime; format = new AudioFormat(reader.WaveFormat); var bytes = new byte[reader.Length]; var read = reader.Read(bytes, 0, bytes.Length); data = new List<byte>(bytes); #else throw new NotImplementedException(); #endif }
private void ProcessFile(WaveStream reader) { int fileLength = (int)reader.Length; byte[] buffer = new byte[fileLength]; reader.Read(buffer, 0, fileLength); ProcessData(buffer, fileLength); }
// Read Mono public static bool TryReadFloat(WaveStream waveStream, out float sampleValue) { // 16 bit PCM data sampleValue = 0f; if (waveStream.WaveFormat.BitsPerSample == 16) { byte[] buffer = new byte[2]; int read = waveStream.Read(buffer, 0, buffer.Length); if (read < buffer.Length) return false; sampleValue = (float)BitConverter.ToInt16(buffer, 0) / 32768f; return true; } return false; }
//private int leftoverSourceOffset = 0; /// <summary> /// Reads bytes from this stream /// </summary> /// <param name="buffer">Buffer to read into</param> /// <param name="offset">Offset in buffer to read into</param> /// <param name="count">Number of bytes to read</param> /// <returns>Number of bytes read</returns> public override int Read(byte[] buffer, int offset, int count) { int bytesRead = 0; if (count % BlockAlign != 0) { //throw new ArgumentException("Must read complete blocks"); count -= (count % BlockAlign); } while (bytesRead < count) { // first copy in any leftover destination bytes int readFromLeftoverDest = Math.Min(count - bytesRead, leftoverDestBytes); if (readFromLeftoverDest > 0) { Array.Copy(conversionStream.DestBuffer, leftoverDestOffset, buffer, offset + bytesRead, readFromLeftoverDest); leftoverDestOffset += readFromLeftoverDest; leftoverDestBytes -= readFromLeftoverDest; bytesRead += readFromLeftoverDest; } if (bytesRead >= count) { // we've fulfilled the request from the leftovers alone break; } // now we'll convert one full source buffer if (leftoverSourceBytes > 0) { // TODO: still to be implemented: see moving the source position back below: } // always read our preferred size, we can always keep leftovers for the next call to Read if we get // too much int sourceBytesRead = sourceStream.Read(conversionStream.SourceBuffer, 0, preferredSourceReadSize); if (sourceBytesRead == 0) { // we've reached the end of the input break; } int sourceBytesConverted; int destBytesConverted = conversionStream.Convert(sourceBytesRead, out sourceBytesConverted); if (sourceBytesConverted == 0) { Debug.WriteLine(String.Format("Warning: couldn't convert anything from {0}", sourceBytesRead)); // no point backing up in this case as we're not going to manage to finish playing this break; } else if (sourceBytesConverted < sourceBytesRead) { // cheat by backing up in the source stream (better to save the lefto sourceStream.Position -= (sourceBytesRead - sourceBytesConverted); } if (destBytesConverted > 0) { int bytesRequired = count - bytesRead; int toCopy = Math.Min(destBytesConverted, bytesRequired); // save leftovers if (toCopy < destBytesConverted) { leftoverDestBytes = destBytesConverted - toCopy; leftoverDestOffset = toCopy; } Array.Copy(conversionStream.DestBuffer, 0, buffer, bytesRead + offset, toCopy); bytesRead += toCopy; } else { // possible error here Debug.WriteLine(string.Format("sourceBytesRead: {0}, sourceBytesConverted {1}, destBytesConverted {2}", sourceBytesRead, sourceBytesConverted, destBytesConverted)); //Debug.Assert(false, "conversion stream returned nothing at all"); break; } } position += bytesRead; return(bytesRead); }
/// <summary> /// Reads bytes from this stream /// </summary> /// <param name="array">Buffer to read into</param> /// <param name="offset">Offset in array to read into</param> /// <param name="count">Number of bytes to read</param> /// <returns>Number of bytes read</returns> public override int Read(byte[] array, int offset, int count) { int bytesRead = 0; if (count % BlockAlign != 0) { //throw new ApplicationException("Must read complete blocks"); count -= (count % BlockAlign); } while (bytesRead < count) { int destBytesRequired = count - bytesRead; int sourceBytes = DestToSource(destBytesRequired); sourceBytes = Math.Min(conversionStream.SourceBuffer.Length, sourceBytes); // temporary fix for alignment problems // TODO: a better solution is to save any extra we convert for the next read /* MRH: ignore this for now - need to check ramifications * if (DestToSource(SourceToDest(sourceBytes)) != sourceBytes) * { * if (bytesRead == 0) * throw new ApplicationException("Not a one-to-one conversion"); * break; * }*/ int sourceBytesRead = sourceStream.Read(conversionStream.SourceBuffer, 0, sourceBytes); if (sourceBytesRead == 0) { break; } int silenceBytes = 0; if (sourceBytesRead % sourceStream.BlockAlign != 0) { // we have been returned something that cannot be converted - a partial // buffer. We will increase the size we supposedly read, and zero out // the end. sourceBytesRead -= (sourceBytesRead % sourceStream.BlockAlign); sourceBytesRead += sourceStream.BlockAlign; silenceBytes = SourceToDest(sourceStream.BlockAlign); } int sourceBytesConverted = 0; int bytesConverted = conversionStream.Convert(sourceBytesRead, out sourceBytesConverted); if (sourceBytesConverted < sourceBytesRead) { // MRH: would normally throw an exception here // back up - is this the right thing to do, not sure sourceStream.Position -= (sourceBytesRead - sourceBytesConverted); } if (bytesConverted > 0) { position += bytesConverted; int availableSpace = array.Length - bytesRead - offset; int toCopy = Math.Min(bytesConverted, availableSpace); //System.Diagnostics.Debug.Assert(toCopy == bytesConverted); // TODO: save leftovers Array.Copy(conversionStream.DestBuffer, 0, array, bytesRead + offset, toCopy); bytesRead += toCopy; if (silenceBytes > 0) { // clear out the final bit Array.Clear(array, bytesRead - silenceBytes, silenceBytes); } } else { break; } } return(bytesRead); }
private int LoadStream(WaveStream waveStream) { if (!isInitialized) { Error("Trying to Load Stream format for uninitialized sound manager"); } int channels, bits_per_sample, sample_rate; byte[] sound_data = null; for (int i = 0; i < managedSounds.Count; ++i) { if (managedSounds[i].refCount <= 0) { StopSound(managedSounds[i].bufferHandle); AL.DeleteBuffer(managedSounds[i].bufferHandle); managedSounds[i].bufferHandle = AL.GenBuffer(); managedSounds[i].refCount = 1; sound_data = new byte[waveStream.Length]; waveStream.Read(sound_data, 0, (int)waveStream.Length); channels = waveStream.WaveFormat.Channels; bits_per_sample = waveStream.WaveFormat.BitsPerSample; sample_rate = waveStream.WaveFormat.SampleRate; AL.BufferData(managedSounds[i].bufferHandle, GetSoundFormat(channels, bits_per_sample), sound_data, sound_data.Length, sample_rate); AL.Source(managedSounds[i].soundSource, ALSourcei.Buffer, managedSounds[i].bufferHandle); return i; } } SoundInstance newSound = new SoundInstance(); newSound.refCount = 1; newSound.bufferHandle = AL.GenBuffer(); newSound.soundSource = AL.GenSource(); sound_data = new byte[waveStream.Length]; waveStream.Read(sound_data, 0, (int)waveStream.Length); channels = waveStream.WaveFormat.Channels; bits_per_sample = waveStream.WaveFormat.BitsPerSample; sample_rate = waveStream.WaveFormat.SampleRate; AL.BufferData(newSound.bufferHandle, GetSoundFormat(channels, bits_per_sample), sound_data, sound_data.Length, sample_rate); AL.Source(newSound.soundSource, ALSourcei.Buffer, newSound.bufferHandle); managedSounds.Add(newSound); return managedSounds.Count - 1; }
public void LoadAudio(String filename) { try { waveStream = new NAudio.Wave.WaveFileReader(filename); } catch (Exception) { MessageBox.Show("Could not load Audio! WAV files only."); return; } if (waveStream != null) { bytesPerSample = (waveStream.WaveFormat.BitsPerSample / 8) * waveStream.WaveFormat.Channels; if (bytesPerSample == 0) bytesPerSample = 1; totalSamples = (int)(waveStream.Length / bytesPerSample); // create a memory based copy so we can access internal data without moving position MemoryStream ms = new MemoryStream((int)waveStream.Length); ms.Position = 0; byte[] waveData = new byte[samplesPerPixel * bytesPerSample]; while (waveStream.Position < waveStream.Length) { int bytesRead = waveStream.Read(waveData, 0, samplesPerPixel * bytesPerSample); ms.Write(waveData, 0, bytesRead); } memoryStream = ms; waveStream = new RawSourceWaveStream(memoryStream, waveStream.WaveFormat); FitToScreen(); } else Reset(); //Zoom(0, 100000); }