我正在使用libPd来生成声音。 LibPd可以处理预定义数量的Ticks,然后使用生成的输出填充float[]
。然后,我转换为BufferedWaveProvider
后使用float[]
存储byte[]
。
音频的生成可以非常快,因此可以在很短的时间内计算1秒的声音,但它也可能很慢,具体取决于Pd补丁。当BufferedWaveProvider
的预留数据量少于预定义数量时,有没有办法触发处理数据?
目前我正在后台线程中生成音频并暂时休眠一段时间,并希望这已经足够了,希望BufferedWaveProvider
不会溢出,甚至何时丢弃该数据。
public void ProcessData(float[] output, int ticks)
{
while (LibPD.Process(ticks, new float[0], output) == 0)
{
if (BufferReady != null)
{
BufferReady(this, new BufferReadyEventArgs(output));
}
Thread.Sleep(999*BlockSize * ticks / 44100);
}
}
public void StartProcessing(float[] output)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(SetPdOutput), output);
}
private void SetPdOutput(object state)
{
float[] output = state as float[];
if (state == null)
{
return;
}
ProcessData(output, Ticks);
}
虽然我将libPd和NAudio粘合在一起的代码是这样的:
Buffer = new float[2 * _player.Ticks * _player.BlockSize]; // stereo, number of Ticks
_soundOutput = new WasapiOut(AudioClientShareMode.Shared, 100);
_audioBuffer = new BufferedWaveProvider(WaveFormat.CreateIeeeFloatWaveFormat(44100, 2))
{
BufferDuration = TimeSpan.FromSeconds(10),
DiscardOnBufferOverflow = true
};
_soundOutput.Init(_audioBuffer);
_soundOutput.Play();
_player.BufferReady += ((sender, eventArgs) =>
{
_audioBuffer.AddSamples(PcmFromFloat(output), 0, output.Length * 4);
});
_player.StartProcessing(Buffer);
答案 0 :(得分:1)
在阅读了NAudio的来源之后,我想出了一个不同的解决方案:编写一个自定义IWaveProvider
,使用与CircularBuffer
类似的BufferedWaveProvider
,但请求新处理过的音频只要阈值不足,就会生成lidPd。
这是操作的要点:
class PdProvider : IWaveProvider
{
readonly CircularBuffer _circularBuffer;
public PdProvider()
{
_buffer = new float[BufferSize];
_player.BufferReady += PdBufferReady;
_circularBuffer = new CircularBuffer(SampleRate * 5); // 5 seconds should be enough for anybody
_minBuffer = SampleRate / 2; // 0.5 second
RefillBuffer();
}
void RefillBuffer()
{
if (_circularBuffer.Count < _minBuffer)
{
// Get data from libPd and add to _circularBuffer
}
}
public int Read(byte[] buffer, int offset, int count)
{
var read = _circularBuffer.Read(buffer, offset, count);
RefillBuffer();
return read;
}
public WaveFormat WaveFormat
{
get
{
return WaveFormat.CreateIeeeFloatWaveFormat(_player.SampleRate, 2);
}
}
}