2012-04-03 247 views
0

我正在使用MATLAB函數來啓動聲音。此功能如下:MATLAB:停止播放聲音

function playTone (duration, toneFreq) 
% Generate a tone 

global player; % as a global variable, sound will continue to play after the function has ended. 
samplesPerSecond = 44100; % the bit rate of the tone 
y = sin(linspace(0, duration * toneFreq * 2 * pi, round(duration * samplesPerSecond))); % the equation of the sound wave 
player = audioplayer(y, samplesPerSecond); % create an audio object from the sound wave at the specified bit rate 
play(player); % play the audio, blocking control until the sound completes 

我希望能夠根據要求停止聲音。我不能使用:

clear playsnd; 

因爲我使用audioplayer()函數(而不是sound()函數)激勵聲音。

我也不能使用:

stop(player); 

,因爲我試圖阻止從父功能的聲音

我有(「???未定義的函數或變量‘球員’。」)如上所述設置我的功能,因爲我需要能夠從子功能產生音調,並且我不能使用sound()函數,因爲我偶爾會收到錯誤消息「無法註冊聲音窗口」。 'player'變量被設置爲全局,以確保在函數完成後聲音繼續播放。

回答

0

你能否修改該函數以便返回播放器的句柄?

function player = playTone (duration, toneFreq) 
% Generate a tone 

global player; % as a global variable, sound will continue to play after the function has ended. 
samplesPerSecond = 44100; % the bit rate of the tone 
y = sin(linspace(0, duration * toneFreq * 2 * pi, round(duration * samplesPerSecond))); % the equation of the sound wave 
player = audioplayer(y, samplesPerSecond); % create an audio object from the sound wave at the specified bit rate 
play(player); % play the audio 

然後您可以稍後使用stop(player)停止它。

類似的問題:How to stop sound in MATLAB?

1

您必須聲明,player是,無論你想,你想阻止玩家使用它,包括一個全局變量:

global player; 
stop(player); 

使用全局變量,然而皺起眉頭。所以我建議你使用傑夫的建議,並返回句柄。