how to play random wav files from one folder with one pushbutton?

3 次查看(过去 30 天)
i want to play random wav files from one folder with only one pushbutton.
the picture above is my .fig screenshot
the logic is if 'Mulai Tes' pushed, i will hear a sound from my wav's folder (i have 5 wav files in my folder) but it will play randomly and it will repeat 3 times per wav. if i heard water sound i will click on the water picture pushbutton and the sound will stop and continue to play the other random sound.
it will be glad if someone can help me to give the code. thank you so much!

回答(1 个)

colordepth
colordepth 2025-3-10
编辑:colordepth 2025-3-10
To implement random playback of .wav files, start by adding a private property like audioPlayer to store the audio object and currentFileName to track the currently playing file. In your "Mulai Tes" button callback, call playNext(app) to begin the playback logic.
function playNext(app)
wavFiles = dir(fullfile(pwd, 'your_folder', '*.wav'));
chosenIdx = randi(numel(wavFiles)); % Random selection
app.currentFileName = wavFiles(chosenIdx).name;
[y, Fs] = audioread(fullfile(wavFiles(chosenIdx).folder, app.currentFileName));
app.audioPlayer = audioplayer(y, Fs);
app.audioPlayer.TimerFcn = @(~,~) playNext(app); % Chain next play
play(app.audioPlayer);
end
For the water button, check if app.currentFileName contains an identifier like 'water' using "contains". If it matches, stop the audioPlayer and call playNext to force the next sound:
function WaterButtonPushed(app, ~)
if contains(app.currentFileName, 'water') % Basic filename check
stop(app.audioPlayer);
playNext(app);
end
end
To enforce 3 plays per sound, consider tracking play counts using a variable. For more details on "audioplayer", refer to the documentation: https://www.mathworks.com/help/matlab/ref/audioplayer.html.

类别

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