Random Notes

Random Notes

January 28, 2021

example p5.js javascript libraries sound genuary

Note: This sounds pretty bad on Android, and sometimes you have to click to hear anything. Coding is fun!

Click here to view this code in the p5 editor.

Click here to view the result by itself.

const minNote = 250;
const maxNote = 500;
const minSpeed = 2;
const maxSpeed = 8;
const margin = 25;

let monoSynth;
let note;
let speed;

let prevNote;
let prevSpeed;

function setup() {
  createCanvas(400, 400);
  monoSynth = new p5.MonoSynth();

  note = random(minNote, maxNote);
  speed = random(minSpeed, maxSpeed);
  prevNote = note;
  prevSpeed = speed;


function draw() {

  const frameDivider = floor(60 / speed);

  if (frameCount % frameDivider == 0) {

function playSynth() {

  note += random([-10, 0, 10]);
  note = constrain(note, minNote, maxNote);

  speed += random([-.1, 0, .1]);
  speed = constrain(speed, minSpeed, maxSpeed);

  const velocity = 1;
  const time = 0;
  const duration = 1 / speed;

  monoSynth.play(note, velocity, time, duration);

  const prevSpeedX = map(prevSpeed,
    minSpeed, maxSpeed,
    margin, width - margin);
  const prevNoteY = map(prevNote,
    minNote, maxNote,
    height - margin, margin);
  const speedX = map(speed,
    minSpeed, maxSpeed,
    margin, width - margin);
  const noteY = map(note,
    minNote, maxNote,
    height - margin, margin);

  stroke(random(200, 255));
  line(prevSpeedX, prevNoteY, speedX, noteY);
  prevNote = note;
  prevSpeed = speed;

Click here to view this code in the p5 editor.

Click here to view the result by itself.

This sketch uses the p5.sound library to play random notes. It also draws a line based on the speed and the notes it plays, so you get a visualization of the random “song” it plays.

I created this for the 28th day of Genuary which had a prompt of “Use sound.”

random notes random notes

Remix Ideas

  • Create a different visualization for the random notes. Maybe lower notes become more red, or faster notes fade out.
  • Explore the rest of the p5.sound library and try other classes and functions.
  • Recreate a song using the library. Start with something like “Twinkle, Twinkle, Little Star” and work your way up to your favorite song!

Libraries Examples


Happy Coding is a community of folks just like you learning about coding.
Do you have a comment or question? Post it here!

Comments are powered by the Happy Coding forum. This page has a corresponding forum post, and replies to that post show up as comments here. Click the button above to go to the forum to post a comment!