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;
end

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

1 comment:

  1. Hi,
    it is still problemon ubuntu 12.04(LTS) and Matlab 2012a(7.14) -well, at least for me. Your script works great! Thank you.

    ReplyDelete