我检查了 NAudio 及其WaveStream
相关类,但找不到WaveStream
基于我提供的 PCM 样本创建的内置方法。
理想情况下,我想做这样的事情:
byte[] samples = ...
WaveFormat waveFormat = new WaveFormat(audioSampleRate,
audioBitsPerSample,
audioChannels);
WaveStream waveStream = CreateWaveStreamfromSamples(waveFormat,
samples);
有没有办法使用 NAudio 做到这一点?
在 Hans, Mark 澄清后进行编辑(感谢反馈):
我需要一个可以传递给 的流SoundPlayer.Play
,这不适合WaveStream
. 在我的项目中,我最终实现了以下类,该类采用样本和 aWaveFormat
并且可以通过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();
}
}