3バンドイコライザー (オーディオ) | エフェクター

LOOP
(function() {

    var onDOMContentLoaded = function() {

        window.AudioContext = window.AudioContext || window.webkitAudioContext;

        try {
            // Create the instance of AudioContext
            var context = new AudioContext();
        } catch (error) {
            window.alert(error.message + ' : Please use Chrome or Safari.');
            return;
        }

        // for the instance of AudioBufferSourceNode
        var source = null;

        // for legacy browsers
        context.createGain = context.createGain || context.createGainNode;

        // Create the instance of GainNode (for Master Volume)
        var gain = context.createGain();

        // Equalizer

        // Create the instance of BiquadFilterNode
        var bass   = context.createBiquadFilter();  // for Base
        var middle = context.createBiquadFilter();  // for Middle
        var treble = context.createBiquadFilter();  // for Trable

        // Set type
        bass.type   = (typeof bass.type   === 'string') ? 'lowshelf'  : 3;
        middle.type = (typeof middle.type === 'string') ? 'peaking'   : 5;
        treble.type = (typeof treble.type === 'string') ? 'highshelf' : 4;

        // Set frequency
        bass.frequency.value   =  500;  //  500 Hz
        middle.frequency.value = 1000;  // 1000 Hz
        treble.frequency.value = 2000;  // 2000 Hz

        // Set Q (Quality Factor)
        // bass.Q.value   = Math.SQRT1_2;  // Not used
        middle.Q.value = Math.SQRT1_2;
        // treble.Q.value = Math.SQRT1_2;  // Not used

        // Initialize Gain
        bass.gain.value   = document.getElementById('range-equalizer-bass').valueAsNumber;
        middle.gain.value = document.getElementById('range-equalizer-middle').valueAsNumber;
        treble.gain.value = document.getElementById('range-equalizer-treble').valueAsNumber;

        // for drawing spectrum

        // Create the instance of AnalyserNode
        var analyser = context.createAnalyser();

        analyser.minDecibels = -150;  // Default -100 dB
        analyser.maxDecibels =    0;  // Default  -30 dB

        var canvas        = document.querySelector('canvas');
        var canvasContext = canvas.getContext('2d');

        var timerid = null;

        var drawSpectrum = function() {
            var width  = canvas.width;
            var height = canvas.height;

            var paddingTop    = 20;
            var paddingBottom = 20;
            var paddingLeft   = 30;
            var paddingRight  = 30;

            var innerWidth  = width  - paddingLeft - paddingRight;
            var innerHeight = height - paddingTop  - paddingBottom;
            var innerBottom = height - paddingBottom;

            var range = analyser.maxDecibels - analyser.minDecibels;  // 70 dB

            // Frequency Resolution
            var fsDivN = context.sampleRate / analyser.fftSize;

            // This value is the number of samples during 250 Hz
            var n250Hz = Math.floor(250 / fsDivN);

            // Get data for drawing spectrum (dB)
            var spectrums = new Float32Array(analyser.frequencyBinCount / 4);
            analyser.getFloatFrequencyData(spectrums);

            // Clear previous data
            canvasContext.clearRect(0, 0, canvas.width, canvas.height);

            // Draw spectrum (dB)
            canvasContext.beginPath();

            for (var i = 0, len = (spectrums.length / 2); i < len; i++) {
                var x = Math.floor((i / len) * innerWidth) + paddingLeft;
                var y = Math.floor(-1 * ((spectrums[i] - analyser.maxDecibels) / range) * innerHeight) + paddingTop;

                if (i === 0) {
                    canvasContext.moveTo(x, y);
                } else {
                    canvasContext.lineTo(x, y);
                }

                if ((i % n250Hz) === 0) {
                    var text = (250 * (i / n250Hz)) + ' Hz';  // index -> frequency

                    // Draw grid (X)
                    canvasContext.fillStyle = 'rgba(255, 0, 0, 1.0)';
                    canvasContext.fillRect(x, paddingTop, 1, innerHeight);

                    // Draw text (X)
                    canvasContext.fillStyle = 'rgba(255, 255, 255, 1.0)';
                    canvasContext.font      = '12px "Times New Roman"';
                    canvasContext.fillText(text, (x - (canvasContext.measureText(text).width / 2)), (height - 3));
                }
            }

            canvasContext.strokeStyle = 'rgba(0, 0, 255, 1.0)';
            canvasContext.lineWidth   = 4;
            canvasContext.lineCap     = 'round';
            canvasContext.lineJoin    = 'miter';
            canvasContext.stroke();

            // Draw grid and text (Y)
            for (var i = analyser.minDecibels; i <= analyser.maxDecibels; i += 10) {
                var gy = Math.floor(-1 * ((i - analyser.maxDecibels) / range) * innerHeight) + paddingTop;

                // Draw grid (Y)
                canvasContext.fillStyle = 'rgba(255, 0, 0, 1.0)';
                canvasContext.fillRect(paddingLeft, gy, innerWidth, 1);

                // Draw text (Y)
                canvasContext.fillStyle = 'rgba(255, 255, 255, 1.0)';
                canvasContext.font      = '12px "Times New Roman"';
                canvasContext.fillText((i + ' dB'), 3, gy);
            }

            timerid = window.setTimeout(drawSpectrum, 20);
        };

        // Trigger 'ended' event
        var trigger = function() {
            var event = document.createEvent('Event');
            event.initEvent('ended', true, true);

            if (source instanceof AudioBufferSourceNode) {
                source.dispatchEvent(event);
            }
        };

        // This funciton is executed after getting ArrayBuffer of audio data
        var startAudio = function(arrayBuffer) {

            // The 2nd argument for decodeAudioData
            var successCallback = function(audioBuffer) {
                // The 1st argument (audioBuffer) is the instance of AudioBuffer

                // If there is previous AudioBufferSourceNode, program stops previous audio
                if ((source instanceof AudioBufferSourceNode) && (source.buffer instanceof AudioBuffer)) {
                    // Execute onended event handler
                    trigger();
                    source = null;
                }

                // Create the instance of AudioBufferSourceNode
                source = context.createBufferSource();

                // for legacy browsers
                source.start = source.start || source.noteOn;
                source.stop  = source.stop  || source.noteOff;

                // Set the instance of AudioBuffer
                source.buffer = audioBuffer;

                // Set parameters
                source.playbackRate.value = document.getElementById('range-playback-rate').valueAsNumber;
                source.loop               = document.querySelector('[type="checkbox"]').checked;

                // GainNode (Master Volume) -> AnalyserNode (Visualization) -> AudioDestinationNode (Output)
                gain.connect(analyser);
                analyser.connect(context.destination);

                // Clear connection
                source.disconnect(0);
                bass.disconnect(0);
                middle.disconnect(0);
                treble.disconnect(0);

                if (document.getElementById('toggle-effect').checked) {
                    // Equalizer ON

                    // Connect nodes for effect (Equalizer) sound
                    // AudioBufferSourceNode (Input) -> BiquadFilterNode (Bass -> Middle -> Treble) -> GainNode (Master Volume) (-> AnalyserNode (Visualization) -> AudioDestinationNode (Output))
                    source.connect(bass);
                    bass.connect(middle);
                    middle.connect(treble);
                    treble.connect(gain);
                } else {
                    // Equalizer OFF

                    // AudioBufferSourceNode (Input) -> GainNode (Master Volume) (-> AnalyserNode (Visualization) -> AudioDestinationNode (Output))
                    source.connect(gain);
                }

                // Start audio
                source.start(0);

                // Start drawing spectrum
                drawSpectrum();

                // Set Callback
                source.onended = function(event) {
                    // Remove event handler
                    source.onended     = null;
                    document.onkeydown = null;

                    // Stop audio
                    source.stop(0);

                    // Stop drawing spectrum
                    if (timerid !== null) {
                        window.clearTimeout(timerid);
                        timerid = null;
                    }

                    console.log('STOP by "on' + event.type + '" event handler !!');

                    // Audio is not started !!
                    // It is necessary to create the instance of AudioBufferSourceNode again

                    // Cannot replay
                    // source.start(0);
                };

                // Stop audio
                document.onkeydown = function(event) {
                    // Space ?
                    if (event.keyCode !== 32) {
                        return;
                    }

                    // Execute onended event handler
                    trigger();

                    return false;
                };
            };

            // The 3rd argument for decodeAudioData
            var errorCallback = function(error) {
                if (error instanceof Error) {
                    window.alert(error.message);
                } else {
                    window.alert('Error : "decodeAudioData" method.');
                }
            };

            // Create the instance of AudioBuffer (Asynchronously)
            context.decodeAudioData(arrayBuffer, successCallback, errorCallback);
        };

        /*
         * File Uploader
         */

        document.getElementById('file-upload-audio').addEventListener('change', function(event) {
            var uploader     = this;
            var progressArea = document.getElementById('progress-file-upload-audio');

            // Get the instance of File (extends Blob)
            var file = event.target.files[0];

            if (!(file instanceof File)) {
                window.alert('Please upload file.');
            } else if (file.type.indexOf('audio') === -1) {
                window.alert('Please upload audio file.');
            } else {
                // Create the instance of FileReader
                var reader = new FileReader();

                reader.onprogress = function(event) {
                    if (event.lengthComputable && (event.total > 0)) {
                        var rate = Math.floor((event.loaded / event.total) * 100);
                        progressArea.textContent = rate + ' %';
                    }
                };

                reader.onerror = function() {
                    window.alert('FileReader Error : Error code is ' + reader.error.code);
                    uploader.value = '';
                };

                // Success read
                reader.onload = function() {
                    var arrayBuffer = reader.result;  // Get ArrayBuffer

                    startAudio(arrayBuffer);

                    uploader.value           = '';
                    progressArea.textContent = file.name;
                };

                // Read the instance of File
                reader.readAsArrayBuffer(file);
            }
        }, false);

        // Control Master Volume
        document.getElementById('range-volume').addEventListener('input', function() {
            var min = gain.gain.minValue || 0;
            var max = gain.gain.maxValue || 1;

            if ((this.valueAsNumber >= min) && (this.valueAsNumber <= max)) {
                gain.gain.value = this.valueAsNumber;
                document.getElementById('output-volume').textContent = this.value;
            }
        }, false);

        // Control playbackRate
        document.getElementById('range-playback-rate').addEventListener('input', function() {
            if (source instanceof AudioBufferSourceNode) {
                var min = source.playbackRate.minValue || 0;
                var max = source.playbackRate.maxValue || 1024;

                if ((this.valueAsNumber >= min) && (this.valueAsNumber <= max)) {
                    source.playbackRate.value = this.valueAsNumber;
                }
            }

            document.getElementById('output-playback-rate').textContent = this.value;
        }, false);

        // Toggle loop
        document.querySelector('[type="checkbox"]').addEventListener(EventWrapper.CLICK, function() {
            if (source instanceof AudioBufferSourceNode) {
                source.loop = this.checked;
            }
        }, false);

        // Toggle Effect
        document.getElementById('toggle-effect').addEventListener(EventWrapper.CLICK, function() {
            if (!(source instanceof AudioBufferSourceNode)) {
                return;
            }

            // Clear connection
            source.disconnect(0);
            bass.disconnect(0);
            middle.disconnect(0);
            treble.disconnect(0);

            if (this.checked) {
                // Equalizer ON

                // Connect nodes for effect (Equalizer) sound
                // AudioBufferSourceNode (Input) -> BiquadFilterNode (Bass -> Middle -> Treble) -> GainNode (Master Volume) (-> AnalyserNode (Visualization) -> AudioDestinationNode (Output))
                source.connect(bass);
                bass.connect(middle);
                middle.connect(treble);
                treble.connect(gain);
            } else {
                // Equalizer OFF

                // AudioBufferSourceNode (Input) -> GainNode (Master Volume) (-> AnalyserNode (Visualization) -> AudioDestinationNode (Output))
                source.connect(gain);
            }
        }, false);

        // Control Equalizer Bass
        document.getElementById('range-equalizer-bass').addEventListener('input', function() {
            var min = bass.gain.minValue || -40;
            var max = bass.gain.maxValue ||  40;

            if ((this.valueAsNumber >= min) && (this.valueAsNumber <= max)) {
                bass.gain.value = this.valueAsNumber;
                document.getElementById('output-equalizer-bass').textContent = this.value;
            }
        }, false);

        // Control Equalizer Middle
        document.getElementById('range-equalizer-middle').addEventListener('input', function() {
            var min = middle.gain.minValue || -40;
            var max = middle.gain.maxValue ||  40;

            if ((this.valueAsNumber >= min) && (this.valueAsNumber <= max)) {
                middle.gain.value = this.valueAsNumber;
                document.getElementById('output-equalizer-middle').textContent = this.value;
            }
        }, false);

        // Control Equalizer Treble
        document.getElementById('range-equalizer-treble').addEventListener('input', function() {
            var min = treble.gain.minValue || -40;
            var max = treble.gain.maxValue ||  40;

            if ((this.valueAsNumber >= min) && (this.valueAsNumber <= max)) {
                treble.gain.value = this.valueAsNumber;
                document.getElementById('output-equalizer-treble').textContent = this.value;
            }
        }, false);
    };

    if ((document.readyState === 'interactive') || (document.readyState === 'complete')) {
        onDOMContentLoaded();
    } else {
        document.addEventListener('DOMContentLoaded', onDOMContentLoaded, true);
    }

})();
function EventWrapper(){
}

(function(){
    var click = '';
    var start = '';
    var move  = '';
    var end   = '';

    // Touch Panel ?
    if (/iPhone|iPad|iPod|Android/.test(navigator.userAgent)) {
        click = 'click';
        start = 'touchstart';
        move  = 'touchmove';
        end   = 'touchend';
    } else {
        click = 'click';
        start = 'mousedown';
        move  = 'mousemove';
        end   = 'mouseup';
    }

    EventWrapper.CLICK = click;
    EventWrapper.START = start;
    EventWrapper.MOVE  = move;
    EventWrapper.END   = end;
})();