当我启动振荡器时,将其停止,然后重新启动; 我收到以下错误:
Uncaught InvalidStateError: Failed to execute 'start' on 'OscillatorNode': cannot call start more than once.
Run Code Online (Sandbox Code Playgroud)
显然我可以gain用来"停止"音频,但这让我感到很糟糕.什么是一种更有效的方法来停止振荡器,同时能够再次启动它?
var ctx = new AudioContext();
var osc = ctx.createOscillator();
osc.frequency.value = 8000;
osc.connect(ctx.destination);
function startOsc(bool) {
if(bool === undefined) bool = true;
if(bool === true) {
osc.start(ctx.currentTime);
} else {
osc.stop(ctx.currentTime);
}
}
$(document).ready(function() {
$("#start").click(function() {
startOsc();
});
$("#stop").click(function() {
startOsc(false);
});
});
Run Code Online (Sandbox Code Playgroud)
当前的解决方案(在提问时):http://jsfiddle.net/xbqbzgt2/2/
最终解决方案:http://jsfiddle.net/xbqbzgt2/3/
我正在用 JavaScript 编写一个振荡器,它在正弦波频率之间创建一个扫描(即啁啾)。为了测试,我想将样本(浮点数)写入 wav 文件。我将如何在 Node.js 中做到这一点?我已经看到了很多关于浏览器端的信息,但没有任何特定于 Node 或任何依赖于浏览器 API 的信息。
我有以下代码段,它创建了一个振荡器并以一定的音量播放。我将oscillator变量保留在函数范围之外,以便我可以在需要时用其他函数停止它。
var oscillator = null;
var isPlaying = false;
function play(freq, gain) {
//stop the oscillator if it's already playing
if (isPlaying) {
o.stop();
isPlaying = false;
}
//re-initialize the oscillator
var context = new AudioContext();
//create the volume node;
var volume = context.createGain();
volume.connect(context.destination);
volume.gain.value = gain;
//connect the oscillator to the nodes
oscillator = context.createOscillator();
oscillator.type = 'sine';
oscillator.frequency.value = freq;
oscillator.connect(volume);
oscillator.connect(context.destination);
//start playing
oscillator.start();
isPlaying = true;
//log
console.log('Playing at frequency ' + freq …Run Code Online (Sandbox Code Playgroud)