Skip to content

Instantly share code, notes, and snippets.

@ThuCommix
Created July 5, 2015 20:40
Show Gist options
  • Save ThuCommix/0da916d212cdb18658f4 to your computer and use it in GitHub Desktop.
Save ThuCommix/0da916d212cdb18658f4 to your computer and use it in GitHub Desktop.
private void ReadHeader()
{
var reader = new BinaryReader(_stream);
if (ReadChunk(reader) != "RIFF")
{
throw new Exception("Invalid file format.");
}
reader.ReadInt32();
if (ReadChunk(reader) != "WAVE")
{
throw new Exception("Invalid file format.");
}
if (ReadChunk(reader) != "fmt ")
{
throw new Exception("Invalid file format.");
}
int len = reader.ReadInt32();
if (len < 16)
{
throw new Exception("Invalid file format.");
}
Format = new WaveFormat(22050, 16, 2)
{
Format = (WaveFormats) reader.ReadInt16(),
Channels = reader.ReadInt16(),
SamplesPerSec = reader.ReadInt32(),
AvgBytesPerSec = reader.ReadInt32(),
BlockAlign = reader.ReadInt16(),
BitsPerSample = reader.ReadInt16()
};
len -= 16;
while (len > 0)
{
reader.ReadByte();
len--;
}
while (_stream.Position < _stream.Length && ReadChunk(reader) != "data")
{
}
if (_stream.Position >= _stream.Length)
throw new Exception("Invalid file format.");
_length = reader.ReadInt32();
_position = _stream.Position;
if (_length <= 0)
{
throw new Exception("Invalid WAV file.");
}
if (Format.Format != WaveFormats.Pcm && Format.Format != WaveFormats.Float)
{
throw new Exception("Only PCM files are supported.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment