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

3 Ansichten (letzte 30 Tage)
dea puspa
dea puspa am 26 Jul. 2020
Bearbeitet: colordepth am 10 Mär. 2025
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!

Antworten (1)

colordepth
colordepth am 10 Mär. 2025
Bearbeitet: colordepth am 10 Mär. 2025
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.

Kategorien

Mehr zu Audio I/O and Waveform Generation finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by