Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / LayoutTests / webaudio / resources / oscillator-testing.js
1 // Notes about generated waveforms:
2 //
3 // QUESTION: Why does the wave shape not look like the exact shape (sharp edges)?
4 // ANSWER: Because a shape with sharp edges has infinitely high frequency content.
5 // Since a digital audio signal must be band-limited based on the nyquist frequency (half the sample-rate)
6 // in order to avoid aliasing, this creates more rounded edges and "ringing" in the
7 // appearance of the waveform.  See Nyquist-Shannon sampling theorem:
8 // http://en.wikipedia.org/wiki/Nyquist%E2%80%93Shannon_sampling_theorem
9 //
10 // QUESTION: Why does the very end of the generated signal appear to get slightly weaker?
11 // ANSWER: This is an artifact of the algorithm to avoid aliasing.
12
13 var sampleRate = 44100.0;
14 var nyquist = 0.5 * sampleRate;
15 var lengthInSeconds = 4;
16 var lowFrequency = 10;
17 var highFrequency = nyquist + 2000; // go slightly higher than nyquist to make sure we generate silence there
18 var context = 0;
19
20 var OSC = {
21     SINE: 0,
22     SQUARE: 1,
23     SAWTOOTH: 2,
24     TRIANGLE: 3,
25     CUSTOM: 4,
26 };
27
28 function generateExponentialOscillatorSweep(oscillatorType) {
29     // Create offline audio context.
30     context = new webkitOfflineAudioContext(1, sampleRate * lengthInSeconds, sampleRate);
31
32     var osc = context.createOscillator();
33     if (oscillatorType == OSC.CUSTOM) {
34         // Create a simple waveform with three Fourier coefficients.
35         // Note the first values are expected to be zero (DC for coeffA and Nyquist for coeffB).
36         var coeffA = new Float32Array([0, 1, 0.5]);
37         var coeffB = new Float32Array([0, 0, 0]);        
38         var wave = context.createPeriodicWave(coeffA, coeffB);
39         osc.setPeriodicWave(wave);
40     } else {
41         osc.type = oscillatorType;
42     }
43
44     // Scale by 1/2 to better visualize the waveform and to avoid clipping past full scale.
45     var gainNode = context.createGain();
46     gainNode.gain.value = 0.5;
47     osc.connect(gainNode);
48     gainNode.connect(context.destination);
49
50     osc.start(0);
51
52     var nyquist = 0.5 * sampleRate;
53     osc.frequency.setValueAtTime(10, 0);
54     osc.frequency.exponentialRampToValueAtTime(highFrequency, lengthInSeconds);
55
56     context.oncomplete = finishAudioTest;
57     context.startRendering();    
58
59     testRunner.waitUntilDone();
60 }