Trying to play Sound at random times during elapsed time.
9 views (last 30 days)
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
David K. on 2 Oct 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
randomtime(1)=; % since you sorted they will be removed in order
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.