MATLAB:停止播放声音

时间:2012-04-03 10:13:21

标签: matlab audio

我正在使用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()函数,因为我偶尔会收到错误消息"无法注册声音窗口& #34 ;. '玩家'变量设置为全局变量,以确保在函数完成后声音继续播放。

2 个答案:

答案 0 :(得分:1)

你必须声明player是一个全局变量,无论你想在哪里使用它,包括你想要停止播放器的地方:

global player;
stop(player);

然而,使用全局变量是不受欢迎的。所以我建议您使用Geoff的建议,并返回句柄。

答案 1 :(得分: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?