Lazily parse Wav data.

This commit is contained in:
Paul Chote
2016-03-12 13:17:28 +00:00
parent 3e37b717a4
commit 35cb2cb609

View File

@@ -16,12 +16,26 @@ namespace OpenRA.FileFormats
{ {
public class WavLoader : ISoundLoader public class WavLoader : ISoundLoader
{ {
bool IsWave(Stream s)
{
var start = s.Position;
var type = s.ReadASCII(4);
s.Position += 4;
var format = s.ReadASCII(4);
s.Position = start;
return type == "RIFF" && format == "WAVE";
}
bool ISoundLoader.TryParseSound(Stream stream, out ISoundFormat sound) bool ISoundLoader.TryParseSound(Stream stream, out ISoundFormat sound)
{ {
try try
{ {
sound = new WavFormat(stream); if (IsWave(stream))
return true; {
sound = new WavFormat(stream);
return true;
}
} }
catch catch
{ {
@@ -35,39 +49,36 @@ namespace OpenRA.FileFormats
public class WavFormat : ISoundFormat public class WavFormat : ISoundFormat
{ {
public int Channels { get { return channels; } } public int Channels { get { return reader.Value.Channels; } }
public int SampleBits { get { return sampleBits; } } public int SampleBits { get { return reader.Value.BitsPerSample; } }
public int SampleRate { get { return sampleRate; } } public int SampleRate { get { return reader.Value.SampleRate; } }
public float LengthInSeconds { get { return WavReader.WaveLength(stream); } } public float LengthInSeconds { get { return WavReader.WaveLength(stream); } }
public Stream GetPCMInputStream() { return new MemoryStream(rawData); } public Stream GetPCMInputStream() { return new MemoryStream(reader.Value.RawOutput); }
int channels; Lazy<WavReader> reader;
int sampleBits;
int sampleRate;
byte[] rawData;
readonly Stream stream; readonly Stream stream;
public WavFormat(Stream stream) public WavFormat(Stream stream)
{ {
this.stream = stream; this.stream = stream;
var wavReader = new WavReader();
var position = stream.Position; var position = stream.Position;
try reader = Exts.Lazy(() =>
{ {
if (!wavReader.LoadSound(stream)) var wavReader = new WavReader();
throw new InvalidDataException(); try
} {
finally if (!wavReader.LoadSound(stream))
{ throw new InvalidDataException();
stream.Position = position; }
} finally
{
stream.Position = position;
}
rawData = wavReader.RawOutput; return wavReader;
channels = wavReader.Channels; });
sampleBits = wavReader.BitsPerSample;
sampleRate = wavReader.SampleRate;
} }
} }