Why is there latency in this C++ ALSA (Linux audio) program?

  alsa, audio, c++, linux

I am exploring sound generation using C++ in Ubuntu Linux. Here is my code:

#include <iostream>
#include <cmath>
#include <stdint.h>
#include <ncurses.h>

//to compile: make [file_name] && ./[file_name]|aplay


int main()
{
    initscr();

    cbreak();
    noecho();
    nodelay(stdscr, TRUE);

    scrollok(stdscr, TRUE);
    timeout(0);

   for ( int t=0;; t++ )
      {

     int ch = getch();
     if (ch == 'q')
     {
         break;
     }

      uint8_t temp = t;
      std::cout<<temp;

    }
}

When this code is run, I want it to generate sound until I press "q" on my keyboard, after which I want the program to quit. This works fine; however, there is a noticeable delay between pressing the keyboard and the program quitting. This is not due to a delay with ncurses, as when I run the program without std::cout<<temp; (i.e. no sound generated), there is no latency

Is there a way to amend this? If not, how are real-time responsive audio programs written?

Edits and suggestions to the question are welcome. I am a novice to ALSA, so I am not sure if any additional details are required to replicate the bug.

Source: Windows Questions C++

LEAVE A COMMENT