Trying to play Sound at random times during elapsed time.

4 visualizzazioni (ultimi 30 giorni)
Firstly, my problem is that I cannot seem to have matlab play my sound file at my desired times. I want a pseudorandom array so that I know when the sound was played. However, in its current state,
etime==randomTme %doesnt work
because of the lack of input arguments and when I try to use Pauses, it messes up the audio playing and plays for longer than I want it to. So i am not entire sure how to set my elapsed time equal to the seconds I want.
I have my function
function[y,Fs] = soundFun(fileName)
[y,Fs] = audioread(fileName);
t0 = clock;
randomTime = sort(randi(9,3,1));
while etime(clock,t0) < 20
if etime == randomTime
sound(y,Fs);
end
%sound(y,Fs);
%pause(2)
%sound(y,Fs);
end
end

Risposta accettata

David K.
David K. il 2 Ott 2019
So as you noticed, etime == randomTime will not work because etime needs input arguments. So fix that issue with this:
etime(clock,t0) == randomTime
Then, this will still not work because randomTime is a matrix and logical expessions that result in matrices make absolutely no sense to an if statement. That can be fixed as such:
sum(etime(clock,t0) == randomTime)>0
Now as long as the time matches a randomTime it will play. However, we then get the issue where etime is very unlikely to completely match an integer. So, to solve that we toss in a little rounding and to make sure it doesnt play multiple times we can also remove the value from randomTime after playing once.
if sum(round(etime(clock,t0),2) == randomTime)>0
sound(y,Fs);
randomtime(1)=[]; % since you sorted they will be removed in order
end
Lastly, a couple questions for you: How long is the audio clip? If it is more than a second you may end up running over itself and playing multiple at the same time. Matlab does not stop operation when playing a sound so if you want to stop the sound earlier you need to decrease the length of y.
  3 Commenti
Walter Roberson
Walter Roberson il 2 Ott 2019
You can use audioplayer() with playblocking() method to stop operations until the sound completes.
Nikolay N Valov
Nikolay N Valov il 2 Ott 2019
Thank you, I will look at the documentation for both of those!

Accedi per commentare.

Più risposte (0)

Prodotti


Release

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by