我试图避免在停止振荡器时发出丑陋的"咔哒"声,所以我决定尝试一些淡出效果exponentialRampToValueAtTime
.像这样:
var playButton = document.getElementById('play');
var stopButton = document.getElementById('stop');
var context = new AudioContext();
var gainNode = context.createGain();
var oscillator = context.createOscillator();
gainNode.connect(context.destination);
oscillator.connect(gainNode);
gainNode.gain.setValueAtTime(1, context.currentTime);
oscillator.start();
gainNode.gain.exponentialRampToValueAtTime(0.0001, context.currentTime + 1);
这很有效,没有"咔嗒"声,而且减速是平滑的.但是,只要我使用按钮和事件监听器这样做,丑陋的点击就会回来,不知何故,斜坡下降更加粗暴
顺便说一句,请在按下"停止"之后等待1秒钟,然后重新按"播放"或丑陋的事情发生:)
var playButton = document.getElementById('play');
var stopButton = document.getElementById('stop');
var context = new AudioContext();
var gainNode = context.createGain();
var oscillator;
gainNode.connect(context.destination);
playButton.addEventListener('click', function() {
oscillator = context.createOscillator();
oscillator.connect(gainNode);
gainNode.gain.setValueAtTime(1, context.currentTime);
oscillator.start();
}, false);
stopButton.addEventListener('click', function() {
gainNode.gain.exponentialRampToValueAtTime(0.0001, context.currentTime + 1);
setTimeout(function(){
oscillator.stop();
}, 1000)
}, false);
我在这里显然缺少一些理论.除了听众之外,代码非常相似,两个片段的结果在质量上有很大差异.你能解释一下这个差异来自哪里吗?
有没有办法在使用按钮/听众时实现第一个片段质量?
谢谢!
问题是斜坡是从先前安排的值完成的,在这种情况下,当您按下播放按钮时.如果在安排坡道之前再次设置该值,您将再次获得平滑过渡!
var playButton = document.getElementById('play');
var stopButton = document.getElementById('stop');
var context = new AudioContext();
var gainNode = context.createGain();
var oscillator;
gainNode.connect(context.destination);
playButton.addEventListener('click', function() {
oscillator = context.createOscillator();
oscillator.connect(gainNode);
gainNode.gain.setValueAtTime(1, context.currentTime);
oscillator.start();
}, false);
stopButton.addEventListener('click', function() {
gainNode.gain.setValueAtTime(gainNode.gain.value, context.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.0001, context.currentTime + 1);
setTimeout(function(){
oscillator.stop();
}, 1000)
}, false);