run a loop until a sound plays
5 views (last 30 days)
Show older comments
Gaetano Gaballo
on 16 Feb 2021
Commented: Gaetano Gaballo
on 2 Mar 2021
Hi,
I have written the following code to play a little music while images keep appearing in random order.
The loop now has a simple index going from 1 to 50. However I would like that the random show goes on until the music stops. In other words, I would like to index the loop to the actual duration of the mucis played. There is any way to do that?
Thanks, g.
fullname = 'C:\path of the music file';
[y, Fs] = audioread(fullname);
PO=audioplayer(y,Fs);
play(PO)
for i=1:50
red_shirts = dir('*.png');
numberOfImages = length(red_shirts);
randomIndex = randi(numberOfImages);
randomImage = imread(red_shirts(randomIndex).name);
imshow(randomImage);
end
0 Comments
Accepted Answer
jibrahim
on 18 Feb 2021
% Set this to the folder containing your images
imageFolder = pwd;
imd = imageDatastore(pwd,'IncludeSubfolders',true);
imd = shuffle(imd);
% Set this to your audio file
fullname = 'FunkyDrums-44p1-stereo-25secs.mp3';
[x,fs] = audioread(fullname);
p = audioplayer(x,fs);
play(p)
tnext = 0;
while isplaying(p)
tnext = tnext + fs;
randomImage = read(imd);
imshow(randomImage);
if imd.progress==1 % Reset if you read all the images
imd.reset
end
while p.CurrentSample < tnext && isplaying(p)
pause(1e-3); % wait till next second
end
end
3 Comments
jibrahim
on 2 Mar 2021
Try changing the while loop condition to this:
while p.CurrentSample<=size(x,1)-4*fs
p.CurrentSample holds the sample the player is pointing to, so stay in the loop until you're 4 seconds from the end.
More Answers (0)
See Also
Categories
Find more on Audio and Video Data in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!