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

조회 수: 2 (최근 30일)
dea puspa
dea puspa 2020년 7월 26일
편집: colordepth 2025년 3월 10일
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