0

I need to play sounds upon certain events, and want to minimize processor load, because some image processing is being done too, and processor performance is limited.

For the present, I play only one sound at a time, and I do it as follows:

  • At program startup, sounds are read from .wav files and the raw pcm data are loaded into memory
  • a sound device is opened (snd_pcm_open() in mode SND_PCM_NONBLOCK)
  • a worker thread is started which continously calls snd_pcm_writei() as long as it is fed with data (data->remaining > 0).

Somewhat resumed, the worker thread function is

static void *Thread_Func (void *arg)
{
  thrdata_t     *data = (thrdata_t *)arg;
  snd_pcm_sframes_t res;

  while (1)
  { pthread_mutex_lock (&lock);

    if (data->shall_stop)
    { data->shall_stop = false;
      snd_pcm_drop (data->pcm_device);
      snd_pcm_prepare (data->pcm_device);
      data->remaining = 0;
    }
    if (data->remaining > 0)
    { res = snd_pcm_writei (data->pcm_device, data->bufptr, data->remaining);
      if (res == -EAGAIN) continue;
      if (res < 0)  // error
      { fprintf (stderr, "snd_pcm_writeX() error: %s\n", snd_strerror(result));
        snd_pcm_recover (data->sub_device, res);
      }
      else      // another chunk has been handed over to sound hw
      { data->bufptr += res * bytes_per_frame;
        data->remaining -= res;
      }
      if (data->remaining == 0) snd_pcm_prepare (data->pcm_device);
    }
    pthread_mutex_unlock (&lock);
    usleep (sleep_us);      // processor relief
  }
} // Thread_Func

Ok, so this works well for one sound at a time. How do I play various?

I found dmix, but it seems a tool on user level, to mix streams coming from separate programs.

Furthermore, I found the Simple Mixer Interface in the ALSA Project C Library Interface, without any hint or example or tutorial about how to use all these function described by one line of text each.

As a last resort I could calculate the mean value of all the buffers to be played synchronously. So long I've been avoiding that, hoping that an ALSA solution might use sound hardware resources, thus relieving the main processor.

I'd be thankful for any hint about how to continue.

hreba
  • 107
  • 1
  • 8
  • You could simply open multiple `dmix` devices. But in the same process, adding the samples yourself might be more efficient. – CL. Mar 05 '20 at 15:14
  • Still hoping for hints about the Simple Mixer Interface which might use sound hardware for the arithmetics. – hreba Mar 06 '20 at 09:29
  • That would require sound hardware that can do mixing. – CL. Mar 06 '20 at 09:48

0 Answers0