Random Walk

by kdoodoo

HTML

<script src="https://tonejs.github.io/CDN/r6/Tone.min.js"></script>

JavaScript

var synth = new Tone.SimpleSynth({
	oscillator : {
  	type : "sawtooth8"
  },
	envelope : {
  	attack : 0.1,
    decay : 0.3,
    sustain : 0
  }
}).toMaster();

var melodyNotes = ["Eb2", "Fb2", "Gb2", "A2", "B2", "C3", "E3", "F#3", "A3", "B3", "Db4", "E4"];

var lastIndex = Math.floor(Math.random() * melodyNotes.length);

function nextStep(){
	lastIndex += Math.round(Math.random() * 4 - 2);
  if (lastIndex >= melodyNotes.length){
    lastIndex = 0;
  }
  if (lastIndex < 0){
    lastIndex = melodyNotes.length - 1;
  }
}

for (var i = 0; i < 50; i++){
  var note = melodyNotes[lastIndex];
  synth.triggerAttack(note, i * 0.2);
  nextStep();
}