Android MIDI Library


Source link: https://github.com/LeffelMania/android-midi-lib

Android MIDI Library

This project is mainly for use with Android applications that do not have access to Java's javax.sound.midi library. However, it is a stand-alone Java library with no Android-specific dependencies or considerations.

This code provides an interface to read, manipulate, and write MIDI files. "Playback" is supported as a real-time event dispatch system. This library does NOT include actual audio playback or device interfacing.

Example Usage:

Reading and Writing a MIDI file:

File input = new File("example.mid");
 MidiFile midi = new MidiFile(input);
  ...  File output = new File("output.mid");
 midi.writeToFile(output);

Manipulating a MIDI file's data:

Removing a track:

midi.removeTrack(2);

Removing any event that is not a note from track 1:

MidiTrack track = midi.getTracks().get(1);
  Iterator<MidiEvent> it = track.getEvents().iterator();
 List<MidiEvent> eventsToRemove = new ArrayList<MidiEvent>();
  while(it.hasNext()) {

  MidiEvent event = it.next();

 if(!(event instanceof NoteOn) && !(event instanceof NoteOff))
  {

eventsToRemove.add(event);

  
}
 
}
  for(MidiEvent event : eventsToRemove) {

  track.removeEvent(event);
 
}

Reducing the tempo by half:

MidiTrack tempoTrack = midi.getTracks().get(0);
 Iterator<MidiEvent> it = tempoTrack.getEvents().iterator();
  while(it.hasNext()) {

  MidiEvent event = it.next();

 if(event instanceof Tempo)
  {

Tempo tempoEvent = (Tempo)event;

tempoEvent.setBpm(tempo.getBpm() / 2);

  
}
 
}

Composing a new MIDI file:

// 1. Create some MidiTracks MidiTrack tempoTrack = new MidiTrack();
 MidiTrack noteTrack = new MidiTrack();
  // 2. Add events to the tracks // Track 0 is the tempo map TimeSignature ts = new TimeSignature();
 ts.setTimeSignature(4, 4, TimeSignature.DEFAULT_METER, TimeSignature.DEFAULT_DIVISION);
  Tempo tempo = new Tempo();
 tempo.setBpm(228);
  tempoTrack.insertEvent(ts);
 tempoTrack.insertEvent(tempo);
  // Track 1 will have some notes in it final int NOTE_COUNT = 80;  for(int i = 0; i < NOTE_COUNT; i++) {

  int channel = 0;
  int pitch = 1 + i;
  int velocity = 100;
  long tick = i * 480;
  long duration = 120;

 noteTrack.insertNote(channel, pitch, velocity, tick, duration);
 
}
  // 3. Create a MidiFile with the tracks we created List<MidiTrack> tracks = new ArrayList<MidiTrack>();
 tracks.add(tempoTrack);
 tracks.add(noteTrack);
  MidiFile midi = new MidiFile(MidiFile.DEFAULT_RESOLUTION, tracks);
  // 4. Write the MIDI data to a file File output = new File("exampleout.mid");
 try {

  midi.writeToFile(output);
 
}
 catch(IOException e) {

  System.err.println(e);
 
}

Listening for and processing MIDI events

// Create a new MidiProcessor: MidiProcessor processor = new MidiProcessor(midi);
  // Register for the events you're interested in: EventPrinter ep = new EventPrinter("Individual Listener");
 processor.registerEventListener(ep, Tempo.class);
 processor.registerEventListener(ep, NoteOn.class);
  // or listen for all events: EventPrinter ep2 = new EventPrinter("Listener For All");
 processor.registerEventListener(ep2, MidiEvent.class);
  // Start the processor: processor.start();
// This class will print any event it receives to the console public class EventPrinter implements MidiEventListener {

  private String mLabel;

public EventPrinter(String label)
  {

mLabel = label;
  
}

@Override
  public void onStart(boolean fromBeginning)
  {

if(fromBeginning)

{

 System.out.println(mLabel + " Started!");

}

else

{

 System.out.println(mLabel + " resumed");

}

  
}

@Override
  public void onEvent(MidiEvent event, long ms)
  {

System.out.println(mLabel + " received event: " + event);

  
}

@Override
  public void onStop(boolean finished)
  {

if(finished)

{

 System.out.println(mLabel + " Finished!");

}

else

{

 System.out.println(mLabel + " paused");

}

  
}
 
}

Resources

A simple but powerful Tween / SpriteSheet / ParabolicMotion / animation library for Android TextureView and SurfaceView.

This library has been built in order to provide a Reactive wrapper around the Android Network Service Discovery API and the JmDNS implementation for older devices.

A tiny Android library that makes a very simple horizontal ProgressBar with animation.

Android custom button with centered drawable.

AndroidRPInterpolator is the interpolator library using Rovert Penner's Easing Functions.

Android CheckBox and RadioButton with additional 3rd 'indeterminate' state.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes