MATLAB: Does MATLAB 6.5 (R13) crash or stop playing sounds when I use the SOUND function in a FOR loop

2000corruptcrashloopMATLABmemoryreferencesyncronouswavplaywhilewinwin2k

I am using the SOUND function in a FOR loop. At some point in the loop after MATLAB plays some of the sounds, MATLAB stops playing sounds. After my program has finished I can not play sounds anymore. However, I still can play WAV files using Windows Media Player despite MATLAB not being able to play sounds.
Sometimes I will receive a Windows system error dialog box explaining that a certain address in memory could not be read. Clicking "OK" terminates MATLAB.
Restarting MATLAB does not always solve the problem. The only way to be able to play sounds with MATLAB is to reboot the computer, but when I run my code again the problem reappears.

Best Answer

The Windows operating system contains a bug that causes a crash when multiplexing several audio streams through one output device. The SOUND function is asynchronous, meaning that after the SOUND function is called, it immediately returns control back to the command line or to the file from where it was called. When the SOUND function is used in a loop, it almost always has the problem specified above.
To work around this problem, you can use the AUDIOPLAYER function in a loop. The 'Playblocking' method of the AUDIOPLAYER function does not return control until playback has completed. The following code is an example of the syntax to use with the AUDIOPLAYER function:
load handel
ap = audioplayer(y,Fs);
playblocking(ap);
You can also use the WAVPLAY function with the additional input argument 'sync' to force the sound device to finish playing the sound and then return control back to MATLAB. The following is an example of the syntax to use for the WAVPLAY function:
load chirp;
y1 = y; Fs1 = Fs;
load gong;
wavplay(y1,Fs1,'sync') % The chirp signal finishes before the
wavplay(y,Fs) % gong signal begins playing.
More information about the WAVPLAY and AUDIOPLAYER functions can be found in the help documentation. You can access the help documentation by using the HELP or DOC commands with the following syntax:
help wavplay
doc waveplay
help audioplayer
doc audioplayer