MATLAB: Audioplayer/isplaying won’t exit tight loop

audioplayerisplaying

When trying to determine when an audioplayer object has finished playing a sound, the following code enters an infinite loop:
aobj = audioplayer(rand(10000,1), 48000, 16, 2);
play(aobj);
while isplaying(aobj)
end
while this code doesn't:
aobj = audioplayer(rand(10000,1), 48000, 16, 2);
play(aobj);
while isplaying(aobj)
pause(0.00001);
end
Can somebody explain what's happening? I'm running Matlab 7.13.0.564 (R2011b) on a Mac, OS 10.7.4. Thank you!

Best Answer

I believe AUDIOPLAYER underwent a poorly, possibly undocumented, change at some point. The AUDIOPLAYER object now makes use of an ASYNCIO object, which I do not believe was always the case (although again I am not sure).
Probing your problem a little further, it appears that the isplaying method does not become false until the event queue is flushed no matter how long intervening computations take between PLAY and ISPLAYING.
obj = audioplayer(rand(44.1e3, 1), 44.1e3);
play(obj);
t0 = clock;
cnt = 0;
while etime(clock, t0) < 2
cnt = cnt+1;
end
isplaying(obj)
At a minimum this needs to be documented, and seems like a bug that you should report.
Looking at the code, the isplaying method of an AUDIOPLAYER object is essentially a wrapper for the isOpen method of an +asyncio.Channel object, which is essentially a wrapper for the proprietary asyncioimpl.Channel.isOpen method. Based on as far as TMW will let us look, there is no way to know why this requires the event queue to be flushed. A hint might be the fact that +asyncio.Channel object has an event called "Closed". Maybe the proprietary asyncioimpl.Channel object also has an event that it is listening for (which would require a flush of the event queue), but that is just a guess.
A simple work around is to use some of the available portaudio implementations for presenting sounds.