wait for audio to finish in MATLAB

173 Views Asked by At

I am trying to create a lamp that turns green while the audio is playing and red after the audio is played. I wrote these lines

function PlayxnButtonPushed(app, event)
             if(app.wav_flag == 1 && app.yn_flag ==0)
            app.playingxnLamp.Color = 'g';
            app.player = audioplayer(app.x, app.fs); 
            play(app.player,app.fs);
            while( strcmp(app.player.running,'on') )
  % Waiting for sound to finish
            end 
            app.xn_flag = 1;
            end
           app.xn_flag = 0;
           app.playingxnLamp.Color = 'r';
        end

But they create lag that I eventually have to open the task manager to terminate the program. Any idea about what I should be doing? - TIA

2

There are 2 best solutions below

0
On

Use playblocking instead of play. The playblocking function retains control until playing completes.

function PlayxnButtonPushed(app, event)
if(app.wav_flag == 1 && app.yn_flag ==0)
   app.player = audioplayer(app.x, app.fs);
   app.playingxnLamp.Color = 'g'; 
   playblocking(app.player,app.fs);   %replaced play with playblocking
   app.xn_flag = 1;
end
app.xn_flag = 0;
app.playingxnLamp.Color = 'r';
end
0
On

As our friend said. You must use playblocking instead of play. No need to while loop. consider this:

 app.Lamp.Color = 'g';
 player = audioplayer(y,Fs);
 playblocking(player)
 app.Lamp.Color = 'r';