简体   繁体   English

Naudio缓冲区和实时流

[英]Naudio buffer and realtime streaming

My application is a text-to-speech application. 我的应用程序是文本到语音的应用程序。 I develop a simple class based on NAudio to play the generated wave byte array (taht contains the text to be read). 我基于NAudio开发了一个简单的类来播放生成的wave字节数组(包含要读取的文本)。 Here is my code: 这是我的代码:

private BufferedWaveProvider _bufferedWaveProvider = new BufferedWaveProvider(new WaveFormat(16000, 1));
private WaveOut _waveOut = new WaveOut();

public NAudioPlayer(){
_waveOut.Init(_bufferedWaveProvider);
_waveOut.Play();
}

public void Play(byte[] textBytes){
    _bufferedWaveProvider.ClearBuffer();
    _bufferedWaveProvider.AddSamples(textBytes, 0, textBytes.Length);
}

I do not know how to manage the buffer in order to prevent from full buffer exceptions. 我不知道如何管理缓冲区,以防止出现完整的缓冲区异常。 Reading other posts, I thought about setting the buffer length but I do not what is the maximal size of the byte array (sent by another application). 在阅读其他文章时,我曾考虑过设置缓冲区长度,但是我不知道字节数组的最大大小是多少(由另一个应用程序发送)。 More, I would like to avoid unexpected breaks when playing (so I think that using Thread.sleep to let the buffer discharging would not be a good idea...). 另外,我想避免在播放时意外中断(因此,我认为使用Thread.sleep释放缓冲区不是一个好主意...)。

How can I solve this problem? 我怎么解决这个问题?

Create your own class similar to the code in BufferedWaveProvider , but with a Queue of byte arrays. 创建您自己的类,类似于BufferedWaveProvider的代码,但带有一个字节数组队列。 Each time you have a new bit of audio to play, then put it into the queue. 每次您有新的音频要播放时,然后将其放入队列。 Then in the Read method, return bytes from each queued buffer in turn, until you've reached the end of queued audio, and then return zeroes (it needs to be a never-ending stream, so Read must always return count ). 然后在Read方法中,依次从每个排队的缓冲区返回字节,直到到达排队音频的末尾,然后返回零(它必须是永无休止的流,因此Read必须始终返回count )。 The only tricky bit will be keeping track of where you were up to reading, as it is likely that the number of bytes requested in the Read method will be less than the number of bytes available in a queued buffer. 唯一棘手的问题是跟踪您要去的地方,因为Read方法中请求的字节数可能会少于排队缓冲区中的可用字节数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM