Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Stream constructor to CachedSound #963

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 38 additions & 12 deletions NAudio.Extras/CachedSound.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NAudio.Wave;

Expand All @@ -9,23 +10,48 @@ namespace NAudio.Extras
/// </summary>
public class CachedSound
{
public float[] AudioData { get; }
public WaveFormat WaveFormat { get; }
public float[] AudioData { get; protected set; }
public WaveFormat WaveFormat { get; protected set; }
public CachedSound(string audioFileName)
{
using (var audioFileReader = new AudioFileReader(audioFileName))
{
// TODO: could add resampling in here if required
WaveFormat = audioFileReader.WaveFormat;
var wholeFile = new List<float>((int)(audioFileReader.Length / 4));
var readBuffer = new float[audioFileReader.WaveFormat.SampleRate * audioFileReader.WaveFormat.Channels];
int samplesRead;
while ((samplesRead = audioFileReader.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
wholeFile.AddRange(readBuffer.Take(samplesRead));
}
AudioData = wholeFile.ToArray();
Init(audioFileReader);
}
}

public CachedSound(Stream sound)
{

using (var audioFileReader = new WaveFileReader(sound))
{
Init(audioFileReader);
}
}

protected void Init(WaveStream waveStream)
{
if (!(waveStream is ISampleProvider sampleProvider))
{
sampleProvider = waveStream.ToSampleProvider();
}

// TODO: could add resampling in here if required
WaveFormat = sampleProvider.WaveFormat;
var wholeFile = new List<float>((int)(waveStream.Length / 4));
var readBuffer = new float[WaveFormat.SampleRate * WaveFormat.Channels];
int samplesRead;
while ((samplesRead = sampleProvider.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
wholeFile.AddRange(readBuffer.Take(samplesRead));
}
AudioData = wholeFile.ToArray();

}

protected CachedSound()
{
// no-op but makes this easier on subclasses
}
}
}