我检查了NAudio及其与WaveStream
相关的类,但找不到基于我提供的PCM示例创建WaveStream
的内置方法。
理想情况下,我想执行以下操作:
byte[] samples = ...
WaveFormat waveFormat = new WaveFormat(audioSampleRate,
audioBitsPerSample,
audioChannels);
WaveStream waveStream = CreateWaveStreamfromSamples(waveFormat,
samples);
是否可以使用NAudio做到这一点?
经过Hans,Mark的澄清后,编辑(感谢您的反馈):
我需要一个可以传递给
SoundPlayer.Play
的流,这与WaveStream
不合适。在我的项目中,我最终实现了以下类,该类带有示例和WaveFormat
,并且可以由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();
}
}
最佳答案
不,没有喜欢的东西。但是,您可以创建自己的。 wave \ wavestream \ wavefilereader.cs源代码文件可能是最佳入门。您可以从中剥离一堆东西,用正确初始化的MemoryStream替换waveStream。