I checked NAudio and its related classes WaveStream, but I could not find a built-in way to build WaveStreambased on the PCM samples that I provide.
Ideally, I would like to do something like this:
byte[] samples = ...
WaveFormat waveFormat = new WaveFormat(audioSampleRate,
audioBitsPerSample,
audioChannels);
WaveStream waveStream = CreateWaveStreamfromSamples(waveFormat,
samples);
Is there any way to do this with NAudio?
Edit after clarification from Hans, Mark (thanks for the tip):
I need a stream that I could pass on SoundPlayer.Play, this is not suitable for WaveStream. In my project, I ended up implementing the next class, which takes samples WaveFormatand can be played using SoundPlayer.
public class MemoryWaveStream : Stream
{
public override bool CanSeek { get { return false; } }
public override bool CanWrite { get { return false; } }
public override bool CanRead { get { return true; } }
public override long Length { get { return _waveStream.Length; } }
public override long Position { get { return _waveStream.Position; } set { _waveStream.Position = value; } }
private MemoryStream _waveStream;
public MemoryWaveStream(byte[] sampleData, WaveFormat waveFormat)
{
_waveStream = new MemoryStream();
BinaryWriter bw = new BinaryWriter(_waveStream);
bw.Write(new char[4] { 'R', 'I', 'F', 'F' });
int length = 36 + sampleData.Length;
bw.Write(length);
bw.Write(new char[8] { 'W', 'A', 'V', 'E', 'f', 'm', 't', ' ' });
waveFormat.Serialize(bw);
bw.Write(new char[4] { 'd', 'a', 't', 'a' });
bw.Write(sampleData.Length);
bw.Write(sampleData, 0, sampleData.Length);
_waveStream.Position = 0;
}
public override int Read(byte[] buffer, int offset, int count)
{
return _waveStream.Read(buffer, offset, count);
}
public override void Flush()
{
_waveStream.Flush();
}
public override long Seek(long offset, SeekOrigin origin)
{
return _waveStream.Seek(offset, origin);
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
}