Ryuclaw.Mac/Ryuclaw.Audio.Shared/WaveReader.cs

58 lines
2.1 KiB
C#
Raw Normal View History

2023-08-28 16:38:06 +00:00
using System;
using System.IO;
namespace Ryuclaw.Audio.Shared
{
public class WaveReader
{
private WaveHeader _header;
public byte[] AudioData { get; private set; }
public WaveReader()
{
_header = new WaveHeader();
AudioData = new byte[0];
}
public void Load(string filePath)
{
using (var stream = new FileStream(filePath, FileMode.Open))
using (var reader = new BinaryReader(stream))
{
// RIFF header
string chunkID = new string(reader.ReadChars(4));
if (chunkID != "RIFF") throw new Exception("Not a valid WAV file.");
var ChunkSize = reader.ReadInt32(); // Chunk size
string format = new string(reader.ReadChars(4));
if (format != "WAVE") throw new Exception("Not a valid WAV file.");
// fmt sub-chunk
string subchunk1ID = new string(reader.ReadChars(4));
if (subchunk1ID != "fmt ") throw new Exception("Expected fmt chunk.");
int subChunk1Size = reader.ReadInt32();
short audioFormat = reader.ReadInt16();
var NumChannels = reader.ReadInt16();
var SampleRate = reader.ReadInt32();
var ByteRate = reader.ReadInt32(); // Byte rate
var BlockAlign = reader.ReadInt16(); // Block align
var BitsPerSample = reader.ReadInt16();
_header = new WaveHeader(SampleRate, ChunkSize, ByteRate, BitsPerSample, NumChannels, BlockAlign);
if (audioFormat != 1 || subChunk1Size != 16)
{
throw new Exception("Only PCM format WAV files are supported.");
}
// data sub-chunk
string subchunk2ID = new string(reader.ReadChars(4));
if (subchunk2ID != "data") throw new Exception("Expected data chunk.");
int subChunk2Size = reader.ReadInt32();
AudioData = reader.ReadBytes(subChunk2Size);
}
}
}
}