Category Archives: Python

Using aubio and alsaaudio with Python

The code used in this post no longer works. For an up-to-date example, please see demo_alsa.py.

Aubio is an audio analysis library which contains implementations of some useful algorithms, including pitch detection. It can be used with Python (through SWIG), but the documentation is very light and there doesn’t appear to be any Python-specific instructions.

Below is a small program that listens to the default audio input using alsaaudio, finds the pitch and energy of the signal using aubio, and prints the results to stdout. For the program to work, you will need the aubio and alsaaudio Python libraries installed, which can be done in Ubuntu/Debian with the following command:

sudo apt-get install python python-alsaaudio python-aubio

The smpl_t data type referred to in the code can be replaced by Python’s float type, but the fvec_t type must be populated one-by-one using the fvec_write_sample function.

import alsaaudio, struct
from aubio.task import *

# constants
CHANNELS	= 1
INFORMAT	= alsaaudio.PCM_FORMAT_FLOAT_LE
RATE		= 44100
FRAMESIZE	= 1024
PITCHALG	= aubio_pitch_yin
PITCHOUT	= aubio_pitchm_freq

# set up audio input
recorder=alsaaudio.PCM(type=alsaaudio.PCM_CAPTURE)
recorder.setchannels(CHANNELS)
recorder.setrate(RATE)
recorder.setformat(INFORMAT)
recorder.setperiodsize(FRAMESIZE)

# set up pitch detect
detect = new_aubio_pitchdetection(FRAMESIZE,FRAMESIZE/2,CHANNELS,
                                  RATE,PITCHALG,PITCHOUT)
buf = new_fvec(FRAMESIZE,CHANNELS)

# main loop
runflag = 1
while runflag:

  # read data from audio input
  [length, data]=recorder.read()

  # convert to an array of floats
  floats = struct.unpack('f'*FRAMESIZE,data)

  # copy floats into structure
  for i in range(len(floats)):
    fvec_write_sample(buf, floats[i], 0, i)

  # find pitch of audio frame
  freq = aubio_pitchdetection(detect,buf)

  # find energy of audio frame
  energy = vec_local_energy(buf)

  print "{:10.4f} {:10.4f}".format(freq,energy)