Qt Documentation

Audiolevels Example

The audiolevels example shows how feed real-time dynamic data to a graph using Q3DBars.

This example reads the audio levels from a microphone and displays those levels in a bar graph. To increase the load for demonstration purposes, and to make the graph little fancier, slightly modified data is used to fill multiple rows.

The interesting stuff happens in AudioLevels and AudioLevelsIODevice classes, so we concentrate on those and skip explaining the basic Q3DBars functionality - for that see Bars Example.

In the header file for AudioLevelsIODevice class we store pointers to the data proxy and also the data array we give to the proxy, because we reuse the same array to keep memory reallocations to the minimum:

In the source file we define some static constants to define size of the data array and the middle row index, as well as the resolution of the visualization. You may need to adjust these values to get decent performance in low-end devices:

The resolution constant indicates the sample rate, for example, value 8 means every eighth byte from audio input is visualized. This is necessary to make the data readable, as it would otherwise make the graph scroll too fast.

In the AudioLevelsIODevice class constructor we initialize the data array:

m_array->reserve(rowCount);
for (int i =0; i < rowCount; i++)
m_array->append(newQBarDataRow(rowSize));

The AudioLevelsIODevice::writeData function is called whenever there is new audio data available to be visualized. There we move the old data along the rows and insert new data in the beginning of the rows:

We use a couple of techniques here to improve performance. First, we reuse the existing data array, as this allows us to avoid any extra memory allocations in our application code. This also means the data array dimensions do not change, which further improves efficiency in the bar graph renderer. Secondly, since each row is a QVector of bar data items, which do not allocate any data that needs deletion, we can utilize memmove and memcpy functions to quickly move and copy data around.

Note: In the future versions of Qt Data Visualization, QBarDataItem might get extended so that it does allocate some memory to store other optional bar properties besides the value. In use cases where those optional properties are used, using memmove and memcpy could lead to memory leaks, so use them with care.