var symbols = [ 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#' ]; function playNote(note) { var a = document.body.appendChild(document.createElement('audio')); a.src = 'resources/' + escape(note) + '.mp3'; a.autoplay = 'true'; a.addEventListener("ended", function (e) { this.parentNode.removeChild(this); }); } var estart = document.getElementById('start'); var eproduce_and_play = document.getElementById('produce_and_play'); var eproduction = document.getElementById('production'); var eiterations = document.getElementById('iter'); var eoutput = document.getElementById('output'); function produce() { var start = estart.value; var production = eproduction.value; var p_lines = eproduction.value.split('\n').map(function(l) { return l.split('-'); }); p_rules = {}; p_lines.forEach(function(x) { var n = 0; if (n = x[0].match(/\(([\d\.]+)\)/)) { var n = parseFloat(n[1]); var k = x[0].match(/\w\#?/)[0].trim(), v = x[1].trim(); if (!p_rules[k]) p_rules[k] = []; p_rules[k].push([n, v]); p_rules[k].sort(function(a, b) { return a[0] - b[0]; }); } else { var k = x[0].trim(), v = x[1].trim(); if (typeof p_rules[k] == 'object') { alert('do not mix statochastic (0.5) grammars with deterministic.'); throw Exception('err'); } p_rules[k] = v; } }); var start_notes = start.match(/\w\#?/g); for (var i = 0; i < parseInt(eiterations.value, 10); i++) { var start_notes = start_notes.join('').match(/\w\#?/g); start_notes = start_notes.map(function(s) { if (typeof p_rules[s] == 'object') { var r = Math.random(); var sum = 0; for (var i = 0; i < p_rules[s].length; i++) { sum += p_rules[s][i][0]; if (r <= sum) { return p_rules[s][i][1]; } } } else { return (p_rules[s]) || s; } }); } eoutput.value = start_notes.join(''); } function play() { var start_notes = eoutput.value.match(/\w\#?/g); var i = 0; function p() { if (i < start_notes.length) { playNote(start_notes[i]); i++; window.setTimeout(p, 300); } } p(); } eproduce_and_play.onclick = function() { produce(); play(); };