4 Tests that AudioBufferSourceNode supports loop-points with .loopStart and .loopEnd.
9 <script type="text/javascript" src="resources/audio-testing.js"></script>
18 var sampleRate = 44100.0;
19 var numberOfNotes = 72; // play over a 6 octave range
20 var noteDuration = 0.100;
21 var noteSpacing = noteDuration + 0.005; // leave 5ms of silence between each "note"
22 var lengthInSeconds = numberOfNotes * noteSpacing;
27 function createTestBuffer(frequency, sampleRate) {
28 // Create a buffer containing two periods at this frequency.
29 // The 1st half is a pure sine wave period scaled by a linear ramp from 0 -> 1.
30 // The 2nd half of the buffer corresponds exactly to one pure sine wave period.
31 var onePeriodDuration = 1 / frequency;
32 var sampleFrameLength = 2 * onePeriodDuration * sampleRate;
34 var audioBuffer = context.createBuffer(1, sampleFrameLength, sampleRate);
36 var n = audioBuffer.length;
37 var channelData = audioBuffer.getChannelData(0);
39 for (var i = 0; i < n; ++i) {
40 var sample = Math.sin(frequency * 2.0*Math.PI * i / sampleRate);
42 // Linear ramp from 0 -> 1 for the first period.
43 // Stay at 1 for the 2nd period.
44 var scale = i < n / 2 ? i / (n / 2) : 1;
47 channelData[i] = sample;
53 function playNote(time, duration, playbackRate) {
54 var source = context.createBufferSource();
55 source.buffer = buffer;
56 source.playbackRate.value = playbackRate;
58 var gainNode = context.createGain();
59 source.connect(gainNode);
60 gainNode.connect(context.destination);
62 // Loop the 2nd half of the buffer.
63 // We should be able to hear any problems as glitches if the looping incorrectly indexes to
64 // anywhere outside of the desired loop-points, since only the 2nd half is a perfect sine-wave cycle,
65 // while the 1st half of the buffer contains a linear ramp of a sine-wave cycle.
67 source.loopStart = 0.5 * buffer.duration;
68 source.loopEnd = buffer.duration;
70 // Play for the given duration.
72 source.stop(time + duration);
74 // Apply a quick linear fade-out to avoid a click at the end of the note.
75 gainNode.gain.value = 1;
76 gainNode.gain.setValueAtTime(1, time + duration - 0.005);
77 gainNode.gain.linearRampToValueAtTime(0, time + duration);
81 if (!window.testRunner)
84 // Create offline audio context.
85 context = new webkitOfflineAudioContext(2, sampleRate * lengthInSeconds, sampleRate);
87 // Create the test buffer.
88 // We'll loop this with the loop-points set for the 2nd half of this buffer.
89 buffer = createTestBuffer(440.0, sampleRate);
91 // Play all the notes as a chromatic scale.
92 for (var i = 0; i < numberOfNotes; ++i) {
93 var time = i * noteSpacing;
94 var semitone = i - numberOfNotes/2; // start three octaves down
96 // Convert from semitone to rate.
97 var playbackRate = Math.pow(2, semitone / 12);
99 playNote(time, noteDuration, playbackRate);
102 context.oncomplete = finishAudioTest;
103 context.startRendering();
105 testRunner.waitUntilDone();