我正在尝试将 NAudio 与 Reactive Extensions 结合使用,但在让 NAudio 播放音频时遇到了问题。
到目前为止,以下是我的代码:
public class WaveOutPlayer : IDisposable
{
WaveOut wavOut = new WaveOut(WaveCallbackInfo.FunctionCallback());
public WaveOutPlayer(int device, int sampleRate, int channels, IStereoSource source)
{
var provider = new WavProv(source, sampleRate, channels);
provider.SetWaveFormat(sampleRate,channels);
wavOut.Init(provider);
}
private class WavProv : WaveProvider32
{
AutoResetEvent are = new AutoResetEvent(false);
ConcurrentQueue<float> queue = new ConcurrentQueue<float>();
public WavProv(IStereoSource source, int sampleRate, int channels)
{
source.ChannelLeft
.Zip(source.ChannelRight, (ls, rs) => new double[] { ls, rs }) //one sample from each channel
.SelectMany(samps => samps) //convert to samples array l,r,l,r,l
.Buffer(sampleRate * channels * 1) //buffer samplerate*channels*2 seconds
.Select(x => x.ToArray()) // to observable of chunks
.Do(x => { are.Set(); })
.SubscribeOn(NewThreadScheduler.Default)
.Subscribe(data =>
{
//queue.Enqueue((float)data);
data.ToList().ForEach((x) => queue.Enqueue((float)x));
});
}
public override int Read(float[] buffer, int offset, int sampleCount)
{
int itemsRead;
if (!queue.Any()) //No data in the queue
{
//are.WaitOne();
buffer = Enumerable.Repeat(0.0f, sampleCount).ToArray(); //Wait for some data
itemsRead = sampleCount;
}
else
{
//number of items to read is lower of samplecount or items in queue
int itemsToRead = (queue.Count() > sampleCount) ? sampleCount : queue.Count();
for (itemsRead = 0; itemsRead < itemsToRead; itemsRead++)
{
float res;
if(queue.TryDequeue(out res))
buffer[itemsRead + offset] = res; //add items from queue to buffer
}
}
Console.WriteLine("Requested:{0}, Read: {1}",sampleCount, itemsRead);
return itemsRead;
}
}
public void Play()
{
wavOut.Play();
}
public void Dispose()
{
wavOut.Dispose();
}
}
正在调用 Read 方法,并且 Console.WriteLine 显示我总是提供足够的数据。顺便说一句,如果我减慢信号的产生速度,以至于我需要偶尔提供一个全零缓冲区(代码当前不存在),那么我会听到“咔哒”声。
还有其他我错过的问题/陷阱吗?
例如,幅度范围仅在 0-1 之间,还是支持全范围的浮点?
谢谢