Arduino - processing: serial data to toggle mp3 file in minim

tested code

example

import processing.serial.*;
Serial myPort;
String data;    
boolean diag = true; //__________________________________ print diagnostic info

import ddf.minim.*;
Minim minim;
AudioPlayer player;
String song = "data/groove.mp3"; //______________________ select song

void setup_serial() { //_________________________________ USB arduino..
  printArray(Serial.list());
  String portName = Serial.list()[0]; //_________________ adjust 0.. x port
  myPort = new Serial(this, portName, 115200);
  myPort.clear();
  myPort.bufferUntil('\n');
  println("try connect to "+portName);
}

void serialEvent(Serial p) { //__________________________ handle serial data
  data = trim(p.readStringUntil('\n'));
  if (data != null) {
    if (diag) println(data); //__________________________ print every GOOD line
    if (data.equals("L")) song_play(true); //____________ start
    if (data.equals("Q")) song_play(false); //___________ stop
  }
}

void song_play(boolean on) { //__________________________ PLAY / PAUSE
  if ( !on && player.isPlaying() )  player.pause(); //___ stop
  if ( on && !player.isPlaying() )  player.loop(); //____ start  [l] 'L'
}

void setup() {
  size(640, 480);
  minim = new Minim(this);
  player = minim.loadFile(song);
  setup_serial();
  println("we expect keyboard [l] or [q] or USB line 'L' or 'Q' ");
}

void draw() {} 

void keyPressed() {
  if ( key == 'l' ) song_play(true); //__________________ start
  if ( key == 'q' ) song_play(false); //_________________ stop
}


// arduino code tested with arduino IDE 1.8.10 hourly and Board Leonardo

/*

int dt = 1000; // msec between sending

void setup() {
  Serial.begin(115200);
}

void loop() {
  if (  analogRead(0) > 512 )  Serial.println("L");
  else                         Serial.println("Q");
  delay(dt);                              // sample rate
}

*/

prints

[0] "COM1"
[1] "COM7"
try connect to COM7
we expect keyboard [l] or [q] or USB line 'L' or 'Q' 
L
L

1 Like