How can I avoid this 'clicking' sound when I stop playing a sound?

前端 未结 3 2034
别跟我提以往
别跟我提以往 2020-12-30 12:55

I really hope this question stays a programming question and do not end up an Sound Mechanics question... Here goes...

I am doing some experiments in order to figure

3条回答
  •  悲&欢浪女
    2020-12-30 13:46

    There's a brief explanation of why we hear the clicking sound (it's a human ear thing) and good examples of how to get around that using the Web audio API here: http://alemangui.github.io/blog//2015/12/26/ramp-to-value.html

    The main takeaway from the article is that the exponential methods to remove the click work better; exponentialRampToValueAtTime and setTargetAtTime.

    Using setTargetAtTime to remove the click

    var context = new AudioContext();
    var oscillator = context.createOscillator();
    var gainNode = context.createGain();
    
    oscillator.connect(gainNode);
    gainNode.connect(context.destination)
    oscillator.start();
    
    stopButton.addEventListener('click', function() {
        gainNode.gain.setTargetAtTime(0, context.currentTime, 0.015);
    });
    

    Using exponentialRampToValueAtTime to remove the click

    var context = new AudioContext();
    var oscillator = context.createOscillator();
    var gainNode = context.createGain();
    
    oscillator.connect(gainNode);
    gainNode.connect(context.destination)
    
    oscillator.start();
    
    stopButton.addEventListener('click', function() {
        // Important! Setting a scheduled parameter value
        gainNode.gain.setValueAtTime(gainNode.gain.value, context.currentTime); 
    
        gainNode.gain.exponentialRampToValueAtTime(0.0001, context.currentTime + 0.03);
    });
    

    Both of these worked for me in my use case, with exponentialRampToValueAtTime working slightly better. I could still hear a faint click using setTargetAtTime.

提交回复
热议问题