MATLAB Answers

Trying to play Sound at random times during elapsed time.

11 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


Sign in to comment.

Accepted Answer

David K.
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.


Nikolay N Valov
Nikolay N Valov on 2 Oct 2019
I have both audio clips that are 1 second and ones that are 3 seconds. I did not realize that Matlab does not stop operation during audio playing. That makes my output for pausing make more sense. I guess I will use the 1 second audio clips which is fine.
If I wanted to use the 3 second ones, I will probably just write another function which has random pauses of >5 in-between the playing of each sound, so at least that way I work around Matlab not stopping operation.
Walter Roberson
Walter Roberson on 2 Oct 2019
You can use audioplayer() with playblocking() method to stop operations until the sound completes.
Nikolay N Valov
Nikolay N Valov on 2 Oct 2019
Thank you, I will look at the documentation for both of those!

Sign in to comment.

More Answers (0)

Sign in to answer this question.