【问题标题】:MATLAB: Stopping a sound playingMATLAB:停止声音播放
【发布时间】:2012-04-03 10:13:20
【问题描述】:

我正在使用 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' 变量设置为全局变量,以确保函数完成后声音继续播放。

【问题讨论】:

    标签: matlab audio


    【解决方案1】:

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

    global player;
    stop(player);
    

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

    【讨论】:

      【解决方案2】:

      你能修改函数让它返回播放器的句柄吗?

      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?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多