Sample Java / Groovy Code to Play MP3 Sound Clip

Groovy

The groovy programming language is a super version of the java language specification. If you are a java developer, you can either rework this code sample or google elsewhere for an exact java example.

Steps To Test

Here is a sample program originally written in java. Here i’ve used groovy as a convenience. This code requires an mp3 codec which is found in the JLayer project seen here: 1.0.1 so download that jar. The latest version appears to be JLayer 1.0.1 from Nov.2008. This is what i used in this test.

  1. Make a new directory
  2. copy above jar into that directory
  3. place a sound or music clip recorded in the mp3 format into that directory
  4. copy the following groovy source code into that directory
  5. be sure you have a working groovy install from here
  6. open terminal command session
  7. change into that directory
  8. compile source code: groovyc -classpath .:jl1.0.1.jar SampleMP3player.groovy
  9. download my two sample mp3 files at bottom of post and place in same directory. One of these is teardrops.mp3
  10. test code : groovy -classpath .:jl1.0.1.jar SampleMP3player.groovy teardrops.mp3 35

ok, that test plays the mp3 file named teardrops.mp for 35 seconds. The second parameter is optionally an integer number of seconds of duration to play the sound clip (default is 10 sec.s). If your clip is longer, the remainder will not be heard as the .close() method stops the playback after timer expiry. If the sound clip is less than that, task blocks until timer expires even if sound clip finishes playing earlier.

Groovy Source Code

Code Comments

Place the following lines at the top of your source code file named SampleMP3player.groovy

/*************************************************************************
 *  Compilation:  groovyc -classpath .:jl1.0.1.jar SampleMP3player.groovy         (OS X)
 *                groovyc -classpath .;jl1.0.1.jar SampleMP3player.groovy         (Windows)
 *  Execution:    groovy -classpath .:jl1.0.1.jar SampleMP3player filename.mp3  (OS X / Linux)
 *                groovy -classpath .;jl1.0.1.jar SampleMP3player filename.mp3  (Windows)
 *
 *  Plays an MP3 file using the JLayer MP3 library.
 *
 *  Reference:  http://www.javazoom.net/javalayer/sources.html for jlayer jar with mp3 converter
 *
 *  To execute, you will need jl1.0.1.jar from the website above in your working directory with compiled source
 *  along with some .mp3 files in the same dir.
 ************************************************************************
*/
// /Volumes/PENDRIVE/MP3Player $ groovyc -classpath .:jl1.0.1.jar SampleMP3player.groovy
// /Volumes/PENDRIVE/MP3Player $ groovy -classpath .:jl1.0.1.jar SampleMP3player.groovy track6.mp3
// *
// *  redapple:jim /Volumes/PENDRIVE/MP3Player $ groovy -classpath .:jl1.0.1.jar SampleMP3player.groovy teardrops.mp3 35

Code Body

Place the following lines in the same source code file as above and following those comments


import java.io.BufferedInputStream;
import java.io.FileInputStream;
import javazoom.jl.player.Player;

public class SampleMP3player
{
// name of sound to be played – should be an MP3 format
String filename;
Player player;
def timer = new Timer()
int seconds = 10;

// constructor needs name of an MP3 file
public SampleMP3player(fn) {
this.filename = fn;
if (!new File(this.filename).exists() || (!this.filename.toLowerCase().endsWith(“.mp3”)) )
{
println “fatal: need mp3 file name as parameter\nNot found -> sound clip:”+this.filename
help();
} // end of if

} // end of constructor

// constructor needs name of an MP3 file
public SampleMP3player(fn,secs) {
//this.filename = fn;
this(fn);
this.seconds = secs as Integer;
} // end of constructor

/* sample code to try running another process while sound clip plays
// declare a task that runs after 10 seconds
def task = timer.runAfter(10000)
{
println “Actually executed at ${new Date()} for file ${filename}.”

// so while this task has started, wait another 10+ seconds before closing player
// which stops the music & issue an exit to finish the thread & JVM
sleep(new Random().nextInt(10) * 1000);
this.close();
System.exit(0);
}
— */

public void close()
{
if (player != null) player.close();
} // end of close()

// stream an MP3 file to audio output
public void play()
{
try
{
FileInputStream fis = new FileInputStream(filename);
BufferedInputStream bis = new BufferedInputStream(fis);
player = new Player(bis);
}
catch (Exception e)
{
println(“Problem playing file ” + filename);
println e
} // end of try/catch

// use new thread to play in background
new Thread(){
public void run()
{
try { player.play(); }
catch (Exception x) { println x; }
} // end of run()

}.start(); // yes, we gotta start playing the clip in a new thread

} // end of play()

def static help()
{
println “groovy -classpath .:jl1.0.1.jar SampleMP3player \nfatal: need mp3 file name as parameter”
println “=== end ===”;
System.exit(1);
}

// typical main method
public static void main(String[] args)
{
println “=== start ===”;
String soundfilename = null;

if (args.size() 1)
{
mp3 = new SampleMP3player(soundfilename, args[1]);
} // end of if
else
{
mp3 = new SampleMP3player(soundfilename);
} // end of else

mp3.play();

// small example to run a task after some seconds that will close & stop the currently playing sound clip
// for testing, uncomment the next line plus def task method above
// println “Current date is ${new Date()}. Task is executed at ${new Date(mp3.task.scheduledExecutionTime())}.”

// note that we need to do process or task that will take up time as the sound clip stops playing when the .close() method is invoked
sleep(mp3.seconds * 1000);

// when done, stop playing it
println “ready to close() after ${mp3.seconds} seconds”;
mp3.close();

// play from the beginning
//def playthis = “teardrops.mp3”
//mp3 = new SampleMP3player(playthis);
//mp3.play();
System.exit(0);

println “=== end ===”;

} // end of main

} // end of class

enjoy 🙂

Sound Samples

Note that i had to do a funny as wordpress does not allow me to insert .mp3 files into my post so i rename them with a .jpg image suffix. This ensures all the bits reach your directory intact. But you will need to rename the ‘image’ to be able to use these clips.

Click here to download track6-mp3.jpg into your target folder then please rename it as track6.mp3 or look here: https://github.com/jnorthr/track6/tree/master/war/resources

Click here to download the teardrops3.mp3 sound clip into your target folder then please rename it as teardrops.mp3

Directory Layout

My directory looked like this after the above testing was complete.

Folder Content for MP3 Test
Folder Content for MP3 Test

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s