Skip to content

Instantly share code, notes, and snippets.

@kshoji
Created April 8, 2014 05:25
Show Gist options
  • Save kshoji/10094069 to your computer and use it in GitHub Desktop.
Save kshoji/10094069 to your computer and use it in GitHub Desktop.
'javax.sound.midi for Android' example code
public class MidiPlayingFragment extends Fragment {
private Sequencer sequencer = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MidiSystem.initialize(getActivity());
try {
sequencer = MidiSystem.getSequencer();
} catch (MidiUnavailableException e) {
Log.e("USB MIDI Sample", e.getMessage(), e);
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (sequencer != null) {
if (sequencer.isOpen()) {
sequencer.close();
}
sequencer = null;
}
MidiSystem.terminate();
}
Button playButton = (Button) inflated.findViewById(R.id.playButton);
playButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (sequencer != null) {
try {
sequencer.open();
} catch (MidiUnavailableException e) {
Log.e("USB MIDI Sample", e.getMessage(), e);
}
try {
try {
Sequence sequence = MidiSystem.getSequence(getActivity().getAssets().open("furusato.mid"));
sequencer.setSequence(sequence);
sequencer.stop();
sequencer.setTickPosition(0);
sequencer.setLoopStartPoint(0);
sequencer.start();
} catch (IOException e) {
Log.e("USB MIDI Sample", e.getMessage(), e);
}
} catch (InvalidMidiDataException e) {
Log.e("USB MIDI Sample", e.getMessage(), e);
}
}
}
});
Button stopButton = (Button) inflated.findViewById(R.id.stopButton);
stopButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (sequencer != null) {
sequencer.stop();
}
}
});
@VinceMaku
Copy link

How can MidiSystem.initialize(getActivity()); work?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment