(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(); // Parameter for the instance of OscillatorNode var type = oscillator.type; // for legacy browsers context.createGain = context.createGain || context.createGainNode; // Create the instance of GainNode (for Master Volume) var gain = context.createGain(); // Distortion // Create the instance of WaveShaperNode var distortion = context.createWaveShaper(); // Create Distortion curve (Float32Array) // This algorithm is introduced by http://stackoverflow.com/questions/7840347/web-audio-api-waveshapernode var createCurve = function(amount, numberOfSamples) { if ((amount > 0) && (amount < 1)) { var curves = new Float32Array(numberOfSamples); var k = (2 * amount) / (1 - amount); for (var i = 0; i < numberOfSamples; i++) { // LINEAR INTERPOLATION: x := (c - a) * (z - y) / (b - a) + y // a = 0, b = 2048, z = 1, y = -1, c = i var x = (((i - 0) * (1 - (-1))) / (numberOfSamples - 0)) + (-1); curves[i] = ((1 + k) * x) / (1 + k * Math.abs(x)); } return curves; } else { return null; // Clean sound (default value) } }; // Flag for starting or stopping sound var isStop = true; // for drawing sound wave // Create the instance of AnalyserNode var analyser = context.createAnalyser(); 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 middle = (innerHeight / 2) + paddingTop; // Sampling period var period = 1 / context.sampleRate; // This value is the number of samples during 5 msec var n5msec = Math.floor(5 * Math.pow(10, -3) * context.sampleRate); // Get data for drawing sound wave var times = new Uint8Array(analyser.fftSize); analyser.getByteTimeDomainData(times); // Clear previous data canvasContext.clearRect(0, 0, width, height); // Draw sound wave canvasContext.beginPath(); for (var i = 0, len = times.length; i < len; i++) { var x = Math.floor((i / len) * innerWidth) + paddingLeft; var y = Math.floor((1 - (times[i] / 255)) * innerHeight) + paddingTop; if (i === 0) { canvasContext.moveTo(x, y); } else { canvasContext.lineTo(x, y); } // 5 msec ? if ((i % n5msec) === 0) { var sec = i * period; // index -> time var msec = sec * Math.pow(10, 3); // sec -> msec var text = Math.round(msec) + ' msec'; // 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 = '16px "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 (Y) canvasContext.fillStyle = 'rgba(255, 0, 0, 1.0)'; canvasContext.fillRect(paddingLeft, paddingTop, innerWidth, 1); canvasContext.fillRect(paddingLeft, middle, innerWidth, 1); canvasContext.fillRect(paddingLeft, innerBottom, innerWidth, 1); // Draw text (Y) canvasContext.fillStyle = 'rgba(255, 255, 255, 1.0)'; canvasContext.font = '16px "Times New Roman"'; canvasContext.fillText(' 1.00', 3, paddingTop); canvasContext.fillText(' 0.00', 3, middle); canvasContext.fillText('-1.00', 3, innerBottom); timerid = window.setTimeout(drawWave, interval); }; /* * Event Listener */ // Start or Stop sound var PIANO_88S = [ 'A-4', 'A-4h', 'B-4', 'C-3', 'C-3h', 'D-3', 'D-3h', 'E-3', 'F-3', 'F-3h', 'G-3', 'G-3h', 'A-3', 'A-3h', 'B-3', 'C-2', 'C-2h', 'D-2', 'D-2h', 'E-2', 'F-2', 'F-2h', 'G-2', 'G-2h', 'A-2', 'A-2h', 'B-2', 'C-1', 'C-1h', 'D-1', 'D-1h', 'E-1', 'F-1', 'F-1h', 'G-1', 'G-1h', 'A-1', 'A-1h', 'B-1', 'C', 'Ch', 'D', 'Dh', 'E', 'F', 'Fh', 'G', 'Gh', 'A', 'Ah', 'B', 'C1', 'C1h', 'D1', 'D1h', 'E1', 'F1', 'F1h', 'G1', 'G1h', 'A1', 'A1h', 'B1', 'C2', 'C2h', 'D2', 'D2h', 'E2', 'F2', 'F2h', 'G2', 'G2h', 'A2', 'A2h', 'B2', 'C3', 'C3h', 'D3', 'D3h', 'E3', 'F3', 'F3h', 'G3', 'G3h', 'A3', 'A3h', 'B3', 'C4' ]; var pianoKeys = Array.prototype.slice.call(document.querySelectorAll('#piano ul li'), 0); var convertIndex = function(index) { // // The 12 equal temparement // // Min -> A 27.5Hz, Max -> C 4186 Hz // // Example : // A * 1.059463 -> A# (half up) // var FREQUENCY_RATIO = Math.pow(2, (1 / 12)); // about 1.059463; var MIN_A = 27.5; return (MIN_A * Math.pow(FREQUENCY_RATIO, index)); }; pianoKeys.forEach(function(element, index, array) { // Start sound element.addEventListener(EventWrapper.START, function(event) { if (!isStop) { oscillator.stop(0); window.clearTimeout(timerid); } var pianoIndex = PIANO_88S.indexOf(this.id); var frequency = convertIndex(pianoIndex); // Create the instance of OscillatorNode oscillator = context.createOscillator(); // for legacy browsers oscillator.start = oscillator.start || oscillator.noteOn; oscillator.stop = oscillator.stop || oscillator.noteOff; // GainNode (Master Volume) -> AnalyserNode (Visualization) -> AudioDestinationNode (Output); gain.connect(analyser); analyser.connect(context.destination); // Clear connection oscillator.disconnect(0); distortion.disconnect(0); if (document.getElementById('toggle-effect').checked) { // Distortion ON // Connect nodes for effect (Distortion) sound // OscillatorNode (Input) -> WaveShaperNode (Distortion) -> GainNode (Master Volume) (-> AnalyserNode (Visualization) -> AudioDestinationNode (Output)) oscillator.connect(distortion); distortion.connect(gain); } else { // Distortion OFF // OscillatorNode (Input) -> GainNode (Master Volume) (-> AnalyserNode (Visualization) -> AudioDestinationNode (Output)) oscillator.connect(gain); } // Set parameters oscillator.type = type; oscillator.frequency.value = frequency; // Start sound oscillator.start(0); // Start drawing sound wave drawWave(); isStop = false; this.classList.remove('key-off'); this.classList.add('key-on'); }, false); // Stop sound element.addEventListener(EventWrapper.END, function() { if (isStop) { return; } // Stop sound oscillator.stop(0); // Stop drawing sound wave if (timerid !== null) { window.clearTimeout(timerid); timerid = null; } isStop = true; this.classList.remove('key-on'); this.classList.add('key-off'); }, 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); // 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 Draw Interval document.getElementById('range-draw-interval').addEventListener('input', function() { interval = this.valueAsNumber; document.getElementById('output-draw-interval').textContent = this.value; }, false); // Toggle Effect document.getElementById('toggle-effect').addEventListener(EventWrapper.CLICK, function() { // Clear connection oscillator.disconnect(0); distortion.disconnect(0); if (this.checked) { // Distortion ON // Connect nodes for effect (Distortion) sound // OscillatorNode (Input) -> WaveShaperNode (Distortion) -> GainNode (Master Volume) (-> AnalyserNode (Visualization) -> AudioDestinationNode (Output)) oscillator.connect(distortion); distortion.connect(gain); } else { // Distortion OFF // OscillatorNode (Input) -> GainNode (Master Volume) (-> AnalyserNode (Visualization) -> AudioDestinationNode (Output)) oscillator.connect(gain); } }, false); // Control Distortion Curve Amount document.getElementById('range-distortion-curve-amount').addEventListener('input', function() { var min = 0; var max = 1; if ((this.valueAsNumber >= min) && (this.valueAsNumber <= max)) { distortion.curve = createCurve(this.valueAsNumber, parseInt(document.getElementById('select-distortion-curve-size').value)); document.getElementById('output-distortion-curve-amount').textContent = this.value; } }, false); // Control Distortion Curve Size document.getElementById('select-distortion-curve-size').addEventListener('change', function() { distortion.curve = createCurve(document.getElementById('range-distortion-curve-amount').valueAsNumber, parseInt(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; })();