Trying to play Sound at random times during elapsed time.

5 次查看(过去 30 天)
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

采纳的回答

David K.
David K. 2019-10-2
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 个评论
Walter Roberson
Walter Roberson 2019-10-2
You can use audioplayer() with playblocking() method to stop operations until the sound completes.

请先登录,再进行评论。

更多回答(0 个)

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by