ltu
ltu

Reputation: 177

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). 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...).

How can I solve this problem?

Upvotes: 2

Views: 3465

Answers (1)

Mark Heath
Mark Heath

Reputation: 49482

Create your own class similar to the code in BufferedWaveProvider, but with a Queue of byte arrays. 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). 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.

Upvotes: 2

Related Questions