Trouble playing sound data from a function
显示 更早的评论
I have a function for playing a simple noise.
function soundBox(A, Ts, t)
Sound = sin(A:Ts:(t * 1000));
Audio = audioplayer(Sound, 22050);
play(Audio);
end
But it doesn't play the sound when I call soundBox(1,.6,3).
If, however, I run the following script.
Sound = sin(1:.6:3000);
Audio = audioplayer(Sound, 22050);
play(Audio);
I get the sound I'm looking for. The purpose is to have this sound that I can play using one line as a function. I then tried the following alternative function and subsequent one line command, which still didn't play.
function Audio = soundBox(A, Ts, t)
Sound = sin(A:Ts:(t * 1000));
Audio = audioplayer(Sound, 22050);
end
play(soundBox(1,.6,3));
However, if I make it two lines.
snd = soundBox(1,.6,3);
play(snd);
It works. Can someone explain to me what is happening? Why wouldn't this be straightforward and work in the original function?
回答(1 个)
Cris LaPierre
2018-12-22
0 个投票
It has to do with variable scope. The player object created inside the function gets deleted as soon as the function exits (immediately after the line is exectuted), essentially canceling the play before it can happen.
类别
在 帮助中心 和 File Exchange 中查找有关 Audio and Video Data 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!