Skip to content

Instantly share code, notes, and snippets.

@qingfeng
Created April 29, 2020 13:54
Show Gist options
  • Save qingfeng/49a4f7e8ee7baba75ad5bde17916f655 to your computer and use it in GitHub Desktop.
Save qingfeng/49a4f7e8ee7baba75ad5bde17916f655 to your computer and use it in GitHub Desktop.
老代码备份:用Processing处理一首歌曲并播放,然后根据歌曲的节奏通过Arduino驱动LED灯闪烁
import processing.serial.*;
import ddf.minim.*;
import ddf.minim.analysis.*;
import cc.arduino.*;
class BeatListener implements AudioListener
{
private BeatDetect beat;
private AudioPlayer source;
BeatListener(BeatDetect beat, AudioPlayer source)
{
this.source = source;
this.source.addListener(this);
this.beat = beat;
}
void samples(float[] samps)
{
beat.detect(source.mix);
}
void samples(float[] sampsL, float[] sampsR)
{
beat.detect(source.mix);
}
}
Minim minim;
AudioPlayer song;
BeatDetect beat;
BeatListener bl;
Arduino arduino;
int ledPin = 10;
int ledPin2 = 6;
int ledPin3 = 2;
float kickSize, snareSize, hatSize;
void setup() {
size(512, 200, P3D);
minim = new Minim(this);
arduino = new Arduino(this, Arduino.list()[1], 57600);
song = minim.loadFile("music.mp3", 2048);
song.play();
beat = new BeatDetect(song.bufferSize(), song.sampleRate());
beat.setSensitivity(100);
kickSize = snareSize = hatSize = 16;
arduino.pinMode(ledPin, Arduino.OUTPUT);
arduino.pinMode(ledPin2, Arduino.OUTPUT);
arduino.pinMode(ledPin3, Arduino.OUTPUT);
bl = new BeatListener(beat, song);
textFont(createFont("Helvetica", 16));
textAlign(CENTER);
}
void draw() {
background(0);
fill(255);
if(beat.isKick()) {
arduino.digitalWrite(ledPin, Arduino.HIGH); // set the LED on
kickSize = 32;
}
if(beat.isSnare()) {
arduino.digitalWrite(ledPin2, Arduino.HIGH); // set the LED on
snareSize = 32;
}
if(beat.isHat()) {
arduino.digitalWrite(ledPin3, Arduino.HIGH); // set the LED on
hatSize = 32;
}
arduino.digitalWrite(ledPin, Arduino.LOW);
arduino.digitalWrite(ledPin2, Arduino.LOW);
arduino.digitalWrite(ledPin3, Arduino.LOW);
textSize(kickSize);
text("KICK", width/4, height/2);
textSize(snareSize);
text("SNARE", width/2, height/2);
textSize(hatSize);
text("HAT", 3*width/4, height/2);
kickSize = constrain(kickSize * 0.95, 16, 32);
snareSize = constrain(snareSize * 0.95, 16, 32);
hatSize = constrain(hatSize * 0.95, 16, 32);
}
void stop() {
// always close Minim audio classes when you are finished with them
song.close();
// always stop Minim before exiting
minim.stop();
// this closes the sketch
super.stop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment