AudioContext【二】滤波设置

上一篇介绍了无标签播放音频,本篇增加些音效效果,主要的api

  • audioContext.createBiquadFilter

主要设置 frequency, Q两个值 (频率,质量)

    const filter = audioContext.createBiquadFilter();
    filter.frequency.value = number; //取值范围 小于800
    filter.Q.value =  number; //小于1000

常用的类型主要有:

  • lowpass(低通滤波)
  • highpass(高通滤波)
  • bandpass(带通滤波)
filter.type = 'lowpass'

全部代码

(function(){
        const audioContext = new AudioContext();
        const filter = audioContext.createBiquadFilter();
        async function play(){
            const res = await fetch('../file/sound.mp3');
             const arraybuffer = await res.arrayBuffer();
             const audioBuffer = await audioContext.decodeAudioData(arraybuffer);
             const source = audioContext.createBufferSource();
             source.connect(audioContext.destination);
             source.connect(filter);
             filter.connect(audioContext.destination)
             filter.type = 'lowpass';
             console.log(filter)
             filter.frequency.value = 1 ;
             filter.Q.value = 1;
             filter.gain.value = -40;
             source.buffer = audioBuffer;
             source.start();
        }

        document.querySelector('button').onclick = play;
        document.querySelector('#pl').oninput = function(e){ 
            var minValue = 40;
            var value = Math.max(minValue, 800*e.target.value);
            console.log(value)
            filter.frequency.value = value; 
        }
        document.querySelector('#gain').oninput = function(e){ filter.gain.value = e.target.value; console.log(e.target.value)}
        document.querySelector('#pz').oninput = function(e){ filter.Q.value = e.target.value * 1000;  console.log(e.target.value * 30)}
        const fillters = document.querySelectorAll('[name="filter"]')
        for(let i=0; i<fillters.length; i++) {
            fillters[i].onchange = function(e){ console.log(e.target.value); filter.type = e.target.value }
        }
    })()

体验地址

文章来源: AudioContext【二】滤波设置