Random Walk

by Eve Weinberg

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 = ["Eb1", "D2", "B2", "C3", "E3", "F#3", "A3", "B4", "G4", "A5"];
var AltNotes = ["Eb1", "Fb2","Gb2","A2","B2","C3","E3","F#3","A3", "B3"]

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

function nextStep(){
	//walk up with 50% probability, down otherwise
	if (Math.random() > 0.5){
  	lastIndex++;
    lastIndex = Math.min(lastIndex, melodyNotes.length - 1);  
  } else {
  	lastIndex--;
    lastIndex = Math.max(lastIndex, 0);
  }
}

//when this is done..wrap around or jump to a new position, trigger something

for (var i = 0; i < 30; i++){
	var note = melodyNotes[lastIndex];
	synth.triggerAttack(note, i * 0.3);
  //tell it what the last index is
  nextStep();
}

//set an interval to only play 5 notes every 2 seconds
setInterval(function(){
var now = synth.now();
for (var to 5){
var note = melodyNotes[lastIndex];
	synth.triggerAttack(note, i * 0.1+ now);
nextStep();
}

});