Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <html>
- <head>
- <script type="text/javascript">
- var audio_context;
- var script_node;
- var sample_rate;
- var beats_per_second = 4.0;
- var samples_per_beat;
- var note_choices = [ 36, 43, 48, 51, 55, 60, 63, 67, 70, 62, 65 ];
- // middle A = 60;
- function note_to_freq(note) {
- return 440 * Math.pow(2, (note - 60) * (1.0 / 12.0));
- }
- function choose_from_array(a) {
- return a[Math.floor(Math.random() * a.length)];
- }
- window.onload = function() {
- audio_context = new AudioContext();
- sample_rate = audio_context.sampleRate;
- samples_per_beat = sample_rate / beats_per_second;
- script_node = audio_context.createScriptProcessor(4096, 0, 2);
- console.log("setting onaudioprocess");
- var notes = [ choose_from_array(note_choices), choose_from_array(note_choices) ];
- var elapsed_samples = 0;
- script_node.onaudioprocess = function(audio_processing_event) {
- // console.log(".");
- var output_buffer = audio_processing_event.outputBuffer;
- var number_of_samples = output_buffer.length;
- var number_of_channels = output_buffer.numberOfChannels;
- var output_data = [null, null];
- for (var channel = 0; channel < number_of_channels; ++channel) {
- output_data[channel] = output_buffer.getChannelData(channel);
- }
- for (var sample = 0; sample < number_of_samples; ++sample) {
- var envelope = 0.5 * Math.exp(-5.0 * elapsed_samples / sample_rate);
- for (var channel = 0; channel < number_of_channels; ++channel) {
- output_data[channel][sample] = envelope * (Math.sin(Math.PI * 2 * note_to_freq(notes[channel]) * elapsed_samples / sample_rate));
- }
- ++elapsed_samples;
- if (elapsed_samples > samples_per_beat) {
- elapsed_samples = elapsed_samples - samples_per_beat;
- for (var channel = 0; channel < number_of_channels; ++channel) {
- notes[channel] = choose_from_array(note_choices);
- }
- }
- }
- }
- console.log("making connection");
- script_node.connect(audio_context.destination);
- }
- </script>
- </head>
- <body>
- <audio>
- No audio!
- </audio>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement