run a loop until a sound plays

3 次查看(过去 30 天)
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

采纳的回答

jibrahim
jibrahim 2021-2-18
% 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 个评论
jibrahim
jibrahim 2021-3-2
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Audio I/O and Waveform Generation 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by