public unsafe WaveFile(Stream s) { using (BinaryReader br = new BinaryReader(s)) { RIFFChunkDescriptor riffChunkDescriptor = br.ReadStruct <RIFFChunkDescriptor>(); string id = Encoding.ASCII.GetString(riffChunkDescriptor.ChunkID, 4); if (id != "RIFF") { throw new InvalidOperationException("Not a valid wave file ID: " + id); } string format = Encoding.ASCII.GetString(riffChunkDescriptor.Format, 4); if (format != "WAVE") { throw new InvalidOperationException("Not a valid wave file format : " + format); } FmtSubChunk fmtSubChunk = br.ReadStruct <FmtSubChunk>(); string fmtChunkID = Encoding.ASCII.GetString(fmtSubChunk.Subchunk1ID, 4); if (fmtChunkID != "fmt ") { throw new InvalidOperationException("Not a supported fmt sub-chunk ID: " + fmtChunkID); } Format = MapFormat(fmtSubChunk.NumChannels, fmtSubChunk.BitsPerSample); Frequency = fmtSubChunk.SampleRate; // SubChunk2ID br.ReadInt32(); int subchunk2Size = br.ReadInt32(); Data = br.ReadBytes(subchunk2Size); SizeInBytes = subchunk2Size; } }
public WaveFile(Stream s) { using (BinaryReader br = new BinaryReader(s)) { var riffChunkDescriptor = new RIFFChunkDescriptor() { ChunkID = new byte[4], Format = new byte[4] }; br.Read(riffChunkDescriptor.ChunkID, 0, 4); riffChunkDescriptor.ChunkSize = br.ReadInt32(); br.Read(riffChunkDescriptor.Format, 0, 4); var id = Encoding.ASCII.GetString(riffChunkDescriptor.ChunkID, 0, 4); if (id != "RIFF") { throw new InvalidOperationException("Not a valid wave file ID: " + id); } string format = Encoding.ASCII.GetString(riffChunkDescriptor.Format, 0, 4); if (format != "WAVE") { throw new InvalidOperationException("Not a valid wave file format : " + format); } var fmtSubChunk = new FmtSubChunk() { Subchunk1ID = new byte[4] }; br.Read(fmtSubChunk.Subchunk1ID, 0, 4); fmtSubChunk.Subchunk1Size = br.ReadInt32(); fmtSubChunk.AudioFormat = br.ReadInt16(); fmtSubChunk.NumChannels = br.ReadInt16(); fmtSubChunk.SampleRate = br.ReadInt32(); fmtSubChunk.ByteRate = br.ReadInt32(); fmtSubChunk.BlockAlign = br.ReadInt16(); fmtSubChunk.BitsPerSample = br.ReadInt16(); string fmtChunkID = Encoding.ASCII.GetString(fmtSubChunk.Subchunk1ID, 0, 4); if (fmtChunkID != "fmt ") { throw new InvalidOperationException("Not a supported fmt sub-chunk ID: " + fmtChunkID); } Format = MapFormat(fmtSubChunk.NumChannels, fmtSubChunk.BitsPerSample); Frequency = fmtSubChunk.SampleRate; // SubChunk2ID br.ReadInt32(); int subchunk2Size = br.ReadInt32(); Data = br.ReadBytes(subchunk2Size); SizeInBytes = subchunk2Size; } }