MATLAB Answers

Repeat audio in App Designer

16 views (last 30 days)
Mostafa Ibrahim
Mostafa Ibrahim on 18 Feb 2021
Answered: Geoff Hayes on 2 Mar 2021
Hello,
I'm trying to make an app in app desginer and I want to play an audio file in the background the whole time while my app is up and running. I currently have this:
[filename,filepath] = uigetfile('*.mp3','Select a File to Open');
fullname = [filepath, filename];
[a,f] = audioread(filename)
p = audioplayer(a,f)
playblocking(p);
But this allows me to only play the audio file once. I don't want to use a while loop as it will just stay stuck there and I want the app to do other stuff while the audio is playing in the background until for example I click on end button for music or close the app. Is there a way I can do that?
Thanks in advance!

Answers (1)

Geoff Hayes
Geoff Hayes on 2 Mar 2021
Mostafa - you could perhaps use a timer to periodically check the status of the audio player. If it isplaying then you would do nothing, but if it is not playing, then you could start the player again. Something like the following might be adapted to suit your needs for App Designer
function [player, audioPlayerStateTimer] = repeatedAudioPlayerExample
audiodata = load('handel.mat');
player = audioplayer(audiodata.y,audiodata.Fs);
% create the periodic timer to check state of player every 500 millisesconds
audioPlayerStateTimer = timer;
audioPlayerStateTimer.TimerFcn = @restartAudioPlayerIfStopped;
audioPlayerStateTimer.Period = 0.5;
audioPlayerStateTimer.ExecutionMode = 'fixedSpacing';
start(audioPlayerStateTimer)
function restartAudioPlayerIfStopped(hObject, eventdata)
if ~isplaying(player)
fprintf('Restarting audio player.\n');
play(player);
end
end
end
I had thought about perhaps using the StopFcn callback in the audio player object to restart itself when the player stops but that might mean you would have to destroy/clear the player in order to really stop playing.
function [player] = repeatedAudioPlayerExample2
audiodata = load('handel.mat');
player = audioplayer(audiodata.y,audiodata.Fs);
player.StopFcn = @restartAudioPlayerIfStopped;
play(player);
function restartAudioPlayerIfStopped(hObject, eventdata)
if ~isplaying(player)
fprintf('Restarting audio player.\n');
play(player);
end
end
end
Since calling stop(player) will cause the StopFcn callback to fire and so restart the audio, you would need to call delete(player) in order to permanently stop it.

Community Treasure Hunt

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

Start Hunting!