Saturday, August 17, 2013

Changes to Octave Callback Interface

The interface to PortAudio that allows you to write callback functions in Octave underwent slight changes. From now on sound is returned in a single Matrix with one or two columns (depending on number of channels) with as many rows as there are audio frames. An example playing back sine waves of different frequencies on the two channels is given below.

function [ sound, status ] = callback_sine (frames)
  global lphase = 0.0;
  global rphase = 0.0;
  incl = 440.0 / 44100.0;
  incr = 443.0 / 44100.0;
  nl = incl * frames;
  nr = incr * frames;
  left = sin (2.0 * pi * [lphase:incl:lphase+nl]);
  right = sin (2.0 * pi * [rphase:incr:rphase+nr]);
  sound = [left', right'];
  status = 0;
  lphase = lphase + nl;
  rphase = rphase + nr;
An example of it's use is given below.
player = audioplayer(@callback_sine);
# play as long as you want
It is also possible to use Octave functions to process recorded data. An example that writes recorded data in to a text file is given below.

function status = callback_record (sound)
  fid = fopen('record.txt', 'at');
  for index = 1:rows(sound)
    fprintf(fid, "%.4f, %.4f\n", sound(index, 1), sound(index, 2));
  status = 0;
Here is a plot of the resulting file with me clapping three times. Only one channel is plotted.

No comments:

Post a Comment