我在MATLAB中使用sound()函数来生成音调。以下功能在440Hz下播放4秒钟的音调:
duration = 4
toneFreq = 440
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
sound(y, samplesPerSecond); % play the sound wave at the specified bit rate
偶尔(在使用该函数几次之后),我从MATLAB收到错误,说“无法注册声音窗口”。稍微浏览了一下互联网,我注意到这是MATLAB中的一个已知错误(版本R14 SP3),因此一般的建议似乎是使用'audioplayer' function代替。所以,我已将我的代码更新为以下内容:
duration = 4
toneFreq = 440
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); % play the sound wave at the specified bit rate
play(player)
但是,这不会产生音调。任何人都可以帮助使这个新代码有效吗?
答案 0 :(得分:1)
我找到了解决方案 - 问题似乎是当功能退出时音频播放停止。所以,我不得不将play()改为playblocking()。这可以防止控制返回,直到声音结束。然而,它并不是理想的解决方案(在声音仍在播放时将控制权传递回父功能会很好),但现在它会这样做。如果有人可以建议一种方法来控制回来和播放整个声音,我将不胜感激。这是最终的代码:
duration = 4
toneFreq = 440
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); % play the sound wave at the specified bit rate
playblocking(player)
编辑:还发现了一种解决方案,允许在函数退出后继续播放。请参阅MATLAB: Having audioplayer() continue to play after function ends。