xxxxxxxxxx
110
let sequence = ["8n", "8n", "4n", "8n", "8n", "4n", "8n", "8n", "4n"];
let index = [];
let indexed_sequence = [];
let markov = []; //this will be an array of arrays
let index_size;
let durations = [];
let position;
let haveTriggered = false;
let drumNames = ["kick", "snare", "hh", "hho"];
let kit = new Tone.Players({
"kick" : "/samples/kick.mp3",
"snare" : "/samples/snare.mp3",
"hh" : "/samples/hh.mp3",
"hho" : "/samples/hho.mp3"
}).toMaster();
function setup() {
index_size = 0;
//process sequence
let new_item = true;
//step 1: analyze sequence
for(let i =0; i < sequence.length; i++){
new_item = true;
//check if item is new. if not, point to existing index
for(let j = 0; j < index_size; j++){
if(sequence[i] == index[j]){
new_item = false;
indexed_sequence[i] = j;
}
}
if(new_item){
index[index_size] = sequence[i];
indexed_sequence[i] = index_size;
index_size++;
}
}
console.log("raw sequence: "+ sequence);
console.log("index: " + index);
console.log("indexed sequence: " + indexed_sequence);
//step 2: create transition matrix
//create table
for(let i = 0; i < index_size; i++){
markov[i] = [];
}
for(var i = 0; i < indexed_sequence.length; i++){ //for each unique pitch
let current = indexed_sequence[i];
let next_pos = (i + 1) % indexed_sequence.length;
let next = indexed_sequence[next_pos];
markov[current].push(next);
}
//print transition table
for(let i = 0; i < markov.length; i++){
console.log(markov[i]);
}
//step 3: create rhythm
var rhythmLength = 100;
var currentIndex = parseInt(random(0, markov.length)); //start anywhere
for(let i = 0; i < rhythmLength; i++){
var transitionPos = parseInt(random(0, markov[currentIndex].length));
var nextIndex = markov[currentIndex][transitionPos];
currentIndex = nextIndex;
durations.push(index[currentIndex]);
}
console.log("generated rhythm: " + durations);
position = 0;
//play back melody
//create "score"
let part = [];
for(let i = 0; i < durations.length; i++){
let duration = Tone.Time(durations[i]).toSeconds();
let event = {"time": position, "sample": drumNames[floor(random()*4)], "velocity": random(), "duration": duration}; //add duration
part.push(event);
position = position + duration;
console.log(position);
//TODO: replace all "pitches" by "duration"
}
var newPart = new Tone.Part(function(time, value){
kit.get(value.sample).start(time, 0, value.duration, 0, 1);
}, part).start(0);
}
function draw() {
if(kit.loaded && !haveTriggered){
Tone.Transport.start();
haveTriggered = true;
}
}