Rectangle color based on MIDI key

I want to have the rectangle change colour based on which key on my MIDI keyboard is pushed.

Can anyone help?

import themidibus.*;

MidiBus myBus;

void setup() {
  size(1920, 400);
  background(0);
  MidiBus.list();
  myBus = new MidiBus(this, 0, 1);
}

void draw() {
    fill(pitch);
  rect(width/2,height/2,50,50);
}
void noteOn(int channel, int pitch, int velocity) {
  // Receive a noteOn
  println();
  println("Note On:");
  println("Pitch:"+pitch);
  println("Velocity:"+velocity);
}

void noteOff(int channel, int pitch, int velocity) {
  // Receive a noteOff
  println();
  println("Note Off:");
  println("Pitch:"+pitch);
  println("Velocity:"+velocity);
}

Answers

  • edited March 2017

    @Uranhjorten -- I don't have a MIDI keyboard here. What values are you getting from pitch?

    You need to:

    1. set the color mode to HSB colorMode(HSB, minPitch, maxPitch) so that you can change hue with a single number, rather than with three R,G,B numbers -- https://processing.org/reference/colorMode_.html
    2. fill(pitch)

    If you don't want to use pitch colors throughout your sketch, isolate your colorMode style setting by using pushStyle / popStyle https://processing.org/reference/pushStyle_.html

    pushStyle();
    colorMode(HSB,0,127);
    fill(pitch);
    popStyle();
    
  • I'm not sure how the midibus library works, but it prints values around 30-70 when I hit different keys.

    It says something like 'the variable pitch does not exist' when I try fill(pitch); Do I need to return pitch from noteOn, and if so how would I do that?

  • edited March 2017 Answer ✓

    Don't return pitch from noteOn. Instead, either:

    1. Inside noteOn, set fill(pitch)
    2. Or: Create a global variable int mPitch and inside noteOn() assign mPitch = pitch. Use the global mPitch in draw()
  • Thank you! I'll see if that works :)

Sign In or Register to comment.