I am trying to write a simple live sine wave generator from scratch in Qt.

I try not to use any external APIs like ASIO or VST. And I want to generate new audio while playing. (As opposed to the Qt example, it just repeats some samples)

Qt only gives you a QIODevice that you write data to at a fixed sample rate. (If the fixed host sample rate is 44100Hz, you need to deliver exactly 44100 Samples a second)

I need an algorithm or design how to synchronize playback and generating of a sine wave.

Or, what is the general approach to audio generation?

Here are my tries to achieve that:

  1. Two buffers, one gets written to, one gets played, and then swap, synchronized with mutexes

    Problem: Mutexes don't resume audio generate thread fast enough Audio Problem 1

  2. One buffer, that gets played and overwritten periodically

    Problem: Jumps in phase (I tried to fix them) Audio Problem 2

  3. That was also supposed to be a sine wave, I tried to get the phase from the audio stream

    enter image description here

  • 1
    This sounds like an ideal application for a Lock-free ring buffer. If you're searching for that term, you should be finding quite some implementations based on std::atomic instead of heavyweight semaphores or mutexes. – tofro Aug 22 '16 at 9:17
  • @tofro this is exactly what I've been trying to find! – KeksArmee Aug 22 '16 at 17:16

For your first problem you need to build in some small amount of latency to allow the audio driver to buffer up a few milliseconds extra audio data to account for any random system caused jitter.

For your second problem you need to keep a count of how many bytes you have output already and use that to compute the phase of the sine, this way the end of one buffer should align perfectly with the start of the next.

  • I'm using ASIO now, everything works with an extra buffer! I couldn't get it to work with Qt, the latency is too high – KeksArmee Sep 3 '16 at 12:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.