gpt4 book ai didi

c# - 从 PCM 样本创建 WaveStream

转载 作者:行者123 更新时间:2023-11-30 14:18:34 25 4
gpt4 key购买 nike

我检查了 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();
}
}

最佳答案

这是一个类,如果需要,您可以将基于字节数组的 MemoryStream 传递给该类。我可能会在 NAudio 1.4 中包含类似的东西,因为我收到了很多关于如何做到这一点的支持请求。

public class RawSourceWaveStream : WaveStream
{
private Stream sourceStream;
private WaveFormat waveFormat;

public RawSourceWaveStream(Stream sourceStream, WaveFormat waveFormat)
{
this.sourceStream = sourceStream;
this.waveFormat = waveFormat;
}

public override WaveFormat WaveFormat
{
get { return this.waveFormat; }
}

public override long Length
{
get { return this.sourceStream.Length; }
}

public override long Position
{
get
{
return this.sourceStream.Position;
}
set
{
this.sourceStream.Position = value;
}
}

public override int Read(byte[] buffer, int offset, int count)
{
return sourceStream.Read(buffer, offset, count);
}
}

关于c# - 从 PCM 样本创建 WaveStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4271078/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com