Matlab GUI doesn't update the switch value while running

20 views (last 30 days)
I am trying to create a simple GUI which will play and stop sound based on a switch. However, it seems that the button value is not getting updated at all.
Load Sound will simply load the sound file. I want the sound file to play repeatedly until I stop. I tried using a state button, a toggle button, a switch but nothing seems to work. Here is my code:-
% Loading the sound works fine
function Load_Sound(app)
app.Button.Text = 'Wait!!' ;
[y,app.Fs] = audioread('Media1.m4a');
app.y_sec = y((8.1*1e+6 + 0.032*app.Fs):(8.1*1e+6 + 0.239*app.Fs));
app.Button.Text = 'Loaded' ;
end
% Switch value changed function
function SwitchChangedValue(app)
num = 0;
while(1)
sound(app.y_sec,app.Fs);
disp(['Sound is on ' num2str(num)])
disp(app.Switch.Value)
pause(2)
num = num +1;
if(app.Switch.Value==0)
disp(app.Switch.Value)
pause(2)
break
end
end
end
end
%% OR THE FOLLOWING
% StateButton value changed function
function Start_State(app)
value = app.StateButton.Value;
if(value==1)
app.StateButton.Text = 'Stop' ;
else
app.StateButton.Text = 'Start' ;
end
num = 0;
while(1)
sound(app.y_sec,app.Fs);
disp(['Sound is on ' num2str(num)])
disp(app.Switch.Value)
pause(2)
num = num +1;
if(app.StateButton.Value==0)
disp(app.StateButton.Value)
pause(2)
break
end
end
disp(value);
end
My while loop doesn't seem to exit even if the state of the state button or switch is changed. It keeps on running and I have to force shut the program each time. I don't understand why the new value of switch/state is not reflected in the function, when I change the state. Any help will be great. I have been trying to fix this since long time now.

Answers (1)

Image Analyst
Image Analyst on 22 Feb 2020
Put in a drawnow whenever you want ot force the screen to repaint
drawnow;
  4 Comments
Manish Kumar Nayak
Manish Kumar Nayak on 22 Feb 2020
No no, that's working fine. My while loop doesn't exit is my main problem.
Image Analyst
Image Analyst on 22 Feb 2020
You don't have a failsafe. Never use a while loop without a failsafe just in case your main exit condition never happens.
maxIterations = 1e10; % Whatever.
loopCounter = 0;
while loopCounter < maxIterations % Instead of while(1)
% code....
loopCounter = loopCounter + 1;
end
That said, I'm not sure (without running it) why your "break" line never gets hit and so your code never exits the while loop. Try stepping through the code.

Sign in to comment.

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Products


Release

R2016a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!