Trouble playing sound data from a function
Afficher commentaires plus anciens
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?
Réponses (1)
Cris LaPierre
le 22 Déc 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.
Catégories
En savoir plus sur Audio and Video Data dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!