Trouble playing sound data from a function
Show older comments
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?
Answers (1)
Cris LaPierre
on 22 Dec 2018
0 votes
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.
Categories
Find more on Audio and Video Data in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!