周波数領域の波形描画 (dB) | サウンドの視覚化

START / STOP
WAVE TYPE
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
(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;
        }
 
        // Create the instance of OscillatorNode
        var oscillator = context.createOscillator();
 
        // Parameters for the instance of OscillatorNode
        var type      = oscillator.type;
        var frequency = oscillator.frequency.value;
        var detune    = oscillator.detune.value;
 
        // for legacy browsers
        context.createGain = context.createGain || context.createGainNode;
 
        // Create the instance of GainNode
        var gain = context.createGain();
 
        // Flag for starting or stopping sound
        var isStop = true;
 
        // for drawing sound wave (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 interval = document.getElementById('range-draw-interval').valueAsNumber;
 
        var drawWave = 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;
 
            // Frequency resolution
            var fsDivN = context.sampleRate / analyser.fftSize;
 
            // This value is the number of samples during 500 Hz
            var n500Hz = Math.floor(500 / fsDivN);
 
            // Get data for drawing spectrum (dB)
            var spectrums = new Float32Array(analyser.frequencyBinCount / 4);
            analyser.getFloatFrequencyData(spectrums);
 
            // Clear previous data
            canvasContext.clearRect(0, 0, width, height);
 
            // Draw spectrum (dB)
            canvasContext.beginPath();
 
            for (var i = 0, len = spectrums.length; 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 % n500Hz === 0) {
                    var text = (500 * (i / n500Hz)) + ' 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   = 2;
            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(drawWave, interval);
        };
 
        /*
         * Event Listener
         */
 
        // Start or Stop sound
        document.querySelector('button').addEventListener(EventWrapper.CLICK, function() {
            if (isStop) {
                // Create the instance of OscillatorNode
                oscillator = context.createOscillator();
 
                // for legacy browsers
                oscillator.start = oscillator.start || oscillator.noteOn;
                oscillator.stop  = oscillator.stop  || oscillator.noteOff;
 
                // OscillatorNode (Input) -> GainNode (Volume) -> AnalyserNode (Visualization) -> AudioDestinationNode (Output)
                oscillator.connect(gain)
                gain.connect(analyser);
                analyser.connect(context.destination);
 
                // Set parameters
                oscillator.type            = type;
                oscillator.frequency.value = frequency;
                oscillator.detune.value    = detune;
 
                // Start sound
                oscillator.start(0);
 
                // Start drawing sound wave
                drawWave();
 
                isStop = false;
                this.innerHTML = '<span class="icon-pause"></span>';
            } else {
                // Stop sound
                oscillator.stop(0);
 
                // Stop drawing sound wave
                if (timerid !== null) {
                    window.clearTimeout(timerid);
                    timerid = null;
                }
 
                isStop = true;
                this.innerHTML = '<span class="icon-start"></span>';
            }
        }, false);
 
        // Control Draw Interval
        document.getElementById('range-draw-interval').addEventListener('input', function() {
            interval = this.valueAsNumber;
            document.getElementById('output-draw-interval').textContent = this.value;
        }, false);
 
        // Control 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);
 
        // Select type
        document.getElementById('form-wave-type').addEventListener('change', function() {
            for (var i = 0, len = this.elements['radio-wave-type'].length; i < len; i++) {
                if (this.elements['radio-wave-type'][i].checked) {
                    oscillator.type = type = (typeof oscillator.type === 'string') ? this.elements['radio-wave-type'][i].value : i;
                    break;
                }
            }
        }, false);
 
        // Control frequency
        document.getElementById('range-frequency').addEventListener('input', function() {
            var min = oscillator.frequency.minValue || 0;
            var max = oscillator.frequency.maxValue || 100000;
 
            if ((this.valueAsNumber >= min) && (this.valueAsNumber <= max)) {
                oscillator.frequency.value = frequency = this.valueAsNumber;
                document.getElementById('output-frequency').textContent = this.value;
            }
        }, false);
 
        // Control detune
        document.getElementById('range-detune').addEventListener('input', function() {
            var min = oscillator.detune.minValue || -4800;
            var max = oscillator.detune.maxValue ||  4800;
 
            if ((this.valueAsNumber >= min) && (this.valueAsNumber <= max)) {
                oscillator.detune.value = detune = this.valueAsNumber;
                document.getElementById('output-detune').textContent = this.value;
            }
        }, false);
 
        // Select fftSize
        document.getElementById('select-fft-size').addEventListener('change', function() {
            switch (parseInt(this.value)) {
                case   32 :
                case   64 :
                case  128 :
                case  256 :
                case  512 :
                case 1024 :
                case 2048 :
                    analyser.fftSize = this.value;
                    break;
                default :
                    window.alert('The selected FFT size is invalid.');
                    break;
            }
        }, false);
 
        // Control smoothingTimeConstant
        document.getElementById('range-smoothing-time-constant').addEventListener('input', function() {
            var min = 0;
            var max = 1;
 
            if ((this.valueAsNumber >= min) && (this.valueAsNumber <= max)) {
                analyser.smoothingTimeConstant = this.valueAsNumber;
                document.getElementById('output-smoothing-time-constant').textContent = this.value;
            }
        }, false);
    };
 
    if ((document.readyState === 'interactive') || (document.readyState === 'complete')) {
        onDOMContentLoaded();
    } else {
        document.addEventListener('DOMContentLoaded', onDOMContentLoaded, true);
    }
 
})();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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;
})();