MATLAB: Audioplayer

audioplayer

I made GUI in matlab to play .wav. But I have problem, at callback fcn. I put that code
[y,Fs] = wavread('signalExp01-22KHz.wav');
player=audioplayer(y,Fs);
play(player)
but that`s not work.
But I change like this
[y,Fs] = wavread('signalExp01-22KHz.wav');
sound(y,Fs);
that`s work. But I can`t stop music during playing.

Best Answer

The audioplayer object is "scoped". Once no more references to the handle exist, it stops playing and cleans up itself. See Loren's blog:
You need to save a copy of player someplace, but only long enough to let the sound play. You can use a timer with a callback to keep player in scope, and then have the timer callback delete player when it is done playing.
EDIT
Basically your variable player points to an audioplayer object. When there are no variables in memory that point to that audioplayer object, MATLAB deletes the object. MATLAB automatically takes care of the memory management. Your player variable gets deleted when your callback function exits (again MATLAB is taking care of the memory management). The key then is to either prevent your callback function from exiting until after the playing has finished or make sure a copy of player is "saved" someplace else.
The easiest is probably to replace
play(player)
with
playblocking(player)
A slightly better solution might be to do
play(player);
pause(max(size(y))/Fs);
The playblocking method will potentially block everything including callbacks. The pause method will allow callbacks to be processed. Both these methods, however, will halt the linear flow of the program until after the playback has finished. There are ways around this, but it depends on your program (see my comment to your question).