Midi and MP3 generation in Java for online playback

by Daniel Winterstein published 20 August 2009

As part of the Robo-Bach project, I got into making midi and mp3 files from Java. This post describes how I did this without too much pain.

Making MIDI

Java provides classes for working with Midi. These are fairly unpleasant. I used JFugue instead. Here is the code to play s simple tune:

Player player = new Player();
player.play("C D E F G A B");

Nice, no? And the only slightly more complicated code to make a two-voiced tune and save it as a midi file:

Player player = new Player(false);
String tune = "V0 C D E C V1 R R C D E C"// The opening to Frere Jacques
player.saveMidi(tune, new File("mytune.mid"));

Delivering music online (with Javascript controls)

Now suppose you want to play your midi file as part of a webpage. This is not as easy as you might expect.

You can direct the user's browser to the midi file - which might trigger it to play, or might not, and certainly won;t let you control playback.

You could try an applet. But (a) the Java applet is dead. Attitudes towards this range from mild indifference to complete disinterest. And (b) Java applets don't support midi.

So we need to use Flash. Flash also doesn't support midi, but it does support mp3. I embedded an invisible Flash mp3 player using the SoundManager javascript library.

Converting MIDI to MP3

To do this I relied on a call to a Unix process. I used timidity piped through lame, called from Java via Process and a shellscript.

The shell command to convert midi to mp3 is:

timidity -Ow -o - mytune.mid | lame - mytune.mp3