ASCIIMath creating images

Saturday, February 12, 2011

Playing sounds from MATLAB on Unix

While I honestly don't know if it is still a problem with the latest versions of MATLAB, there has been a problem with the "sound()" function in MATLAB on Macs and Linux platforms with ALSA.  Here is a very simple script that works around the problem by simply creating a temporary wave file, then calling the appropriate command-line function to make the sound.  It's trivial to customize.

In contrast to the real "sound()" function, this one also doesn't block, and returns immediately.  Again, this is trivial to change (by removing the ampersand) but I like this behavior, especially useful when playing longer sound files.

function [ ] = usound( w, fs )
%USOUND Plays sound on ALSA-based linux machines or macs

if nargin < 2
    fs = 16000;

filename = ['/tmp/' getenv('USER') '_matplay.wav'];
wavwrite( w, fs, filename );
if ismac
    eval(['!afplay ' filename ' &']);
    eval(['!aplay ' filename ' &']);