play audio within a function MATLAB 2019a

조회 수: 1 (최근 30일)
Af
Af 2019년 10월 29일
댓글: Walter Roberson 2023년 1월 17일
Hi,
I cannot play an audio within a function. for example, if I run the following code in the command window, it works (plays the audio):
DtFl=load(DspFl);
x=DtFl.x; Fs=DtFl.Fs;
Ply = audioplayer(50*x, Fs);
play(Ply)
but if I put the "play" function within another function, nothing happens (no audio play)
function TstAudioPlay
clc; clear
DspFl='E:\WorkrelatedData\VAGSound\Cntrl1Chn2Dt.mat';
DtFl=load(DspFl);
x=DtFl.x; Fs=DtFl.Fs;
runaudio(x,Fs)
function runaudio(x,Fs)
Ply = audioplayer(50*x, Fs);
play(Ply)
the peculiar thing is that if I put a break point before the "play" function and debud the code, the audio plays well.
Any suggestion?
B

채택된 답변

Walter Roberson
Walter Roberson 2019년 10월 29일
You are using play(), which is non-blocking. The audio is started and then the play() call returns. The play() call is the last thing in the function, so the function exits, tearing down the workspace variables, including removing the audioplayer object you constructed inside the function.
You can either use playblocking() or you can construct the audio player object in a location that does not get destroyed when the callbacks return.
  댓글 수: 2
Sujas
Sujas 2023년 1월 17일
편집: Sujas 2023년 1월 17일
But There is a little problem with that,
The function only continues only after the sound is completely done but what is we want to do something simultaneously with sound like while making games.
That's Why Simply Use:
sound(y,Fs)
It will from function also without blocking the whole code!
Walter Roberson
Walter Roberson 2023년 1월 17일

if you construct the audioplayer object in a location that does not get destroyed when the function returns then you can use play() without waiting for the function to return.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Audio and Video Data에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by