import java.io.*; import javax.sound.midi.*; /** * This will play files as songs. Example usage: * * java Java2Midi Java2Midi.class * */ public class Java2Midi { public static void main(String[] args) { new Java2Midi().realMain(args); } public void realMain(String[] args) { if (args.length == 0) { System.err.println("Usage: " + getClass().getSimpleName() + " +"); return; } for (String fileName : args) { try { play(fileName); } catch (IOException e) { e.printStackTrace(); } } } private final static int[] SCALE = { 1, 3, 5, 6, 8, 10, 12, 13, 15, 17, 18, 20, 22, 24, 25, 27, 29, 30, 32, 34, 36, }; private void play(String fileName) throws IOException { if (!fileName.endsWith(".class")) { fileName += ".class"; } Synthesizer synth = null; try { synth = MidiSystem.getSynthesizer(); } catch (MidiUnavailableException e) { e.printStackTrace(); return; } try { synth.open(); } catch (MidiUnavailableException e) { e.printStackTrace(); return; } int channelNumber = 0; MidiChannel channel = null; MidiChannel[] channels = synth.getChannels(); for (;;) { System.out.print("Please select a channel between 1 and " + channels.length + " > "); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String channelNumberString = in.readLine(); if (channelNumberString.trim().equals("")) { channelNumberString = "1"; } in.close(); int num = Integer.MIN_VALUE; try { num = Integer.parseInt(channelNumberString); } catch (NumberFormatException _) {} if (num == Integer.MIN_VALUE) { System.out.println("Invalid choice: " + channelNumberString); } else if (num < 1 || num > channels.length) { System.out.println(num + " must be >= 1 and <= " + channels.length); } else { System.out.println("\nUsing channel " + num + "..."); channel = channels[num-1]; break; } } BufferedInputStream in = new BufferedInputStream(new FileInputStream(fileName)); int duration, note; for (;;) { if ((duration = in.read()) == -1) break; if ((note = in.read()) == -1) break; int scaledDuration = 100 + 4 * duration; int scaledNote = 50 + SCALE[note%SCALE.length]; channel.noteOn(scaledNote,13); try { Thread.sleep(scaledDuration); } catch (InterruptedException _) {} } in.close(); } }