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?

Respuestas (1)

Cris LaPierre
Cris LaPierre el 22 de Dic. de 2018

0 votos

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.

Productos

Versión

R2015a

Preguntada:

el 31 de Ag. de 2018

Respondida:

el 22 de Dic. de 2018

Community Treasure Hunt

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

Start Hunting!

Translated by