Skip to content

Using Circular Buffers

Coloride edited this page May 13, 2024 · 6 revisions

Introduction

A circular buffer, according to Wikipedia is:

Wikipedia definition

Or in short, a buffer that eats, reads into an infinite cycle.

Ring Buffer diagram

Here's a cool diagram that represents a circular buffer.

Why do I need a circular buffer?

A circular buffer can be useful if you have a continuous stream of data that you need to continuously read.

In our case with OpenVoiceSharp, sometimes, a game engine does not support direct streaming and PCM playback natively, meaning that you cannot just feed it raw incoming data & it plays right into your speakers or headphones directly.

So, instead, if the game engine only supports playing a clip, then switch to the next one, we can accumulate the data that's incoming into a "queue" (our circular buffer) and keep on adding the data when we receive it, and once its full or reaches a certain criteria, we can read it. The extra data is ignored until the entire data is read and then cleared.

It can be used for buffering: e.g. to record microphone data, or, e.g. to read the voice data.

Another diagram

The implementation

OpenVoiceSharp comes with a generic Circular Audio Buffer implementation with whatever type of data along with the size of the buffer, as long as its a struct. The following class CircularAudioBuffer<T> (file here) contains all implementation needed.

For a fully fledged example, please see the Unity implementation (soon).

Conclusion

Soon