/************************************************************************* * Compilation: javac -classpath .:jl1.0.jar MP3.java (OS X) * javac -classpath .;jl1.0.jar MP3.java (Windows) * Execution: java -classpath .:jl1.0.jar MP3 filename.mp3 (OS X / Linux) * java -classpath .;jl1.0.jar MP3 filename.mp3 (Windows) * * Plays an MP3 file using the JLayer MP3 library. * * Reference: http://www.javazoom.net/javalayer/sources.html * * To execute, get the file jl1.0.jar from the above Web site and put * it in your working directory with this (or an equivalent) file. * *************************************************************************/ import java.io.BufferedInputStream; import java.io.FileInputStream; // For the following 'import' line to work, the file jl1.0.jar (included with // this class file) must be added to the current working directory (classpath) import javazoom.jl.player.Player; public class SoundPlayStopWithMP3 { private String filename; private Player player; // Note that this 'main' method is part of this class for demonstration // purposes only; an instance of this MP3 player class would normally // be called from a separate file public static void main(String[] args) { String filename = "data_files/musicboxdancer.mp3"; SoundPlayStopWithMP3 mp3 = new SoundPlayStopWithMP3(filename); mp3.play(); // Since the MP3 plays in the background, any additional code that // follows the call to the 'play' method will execute IMMEDIATELY // after the MP3 starts playing System.out.println("The MP3 has started playing."); } // Constructor that takes the name of an MP3 file public SoundPlayStopWithMP3(String filename) { this.filename = filename; } // Stop playing the MP3 file public void close() { if (player != null) player.close(); } // Play the MP3 file through the computer's sound card public void play() { try { FileInputStream fis = new FileInputStream(filename); BufferedInputStream bis = new BufferedInputStream(fis); player = new Player(bis); } catch (Exception error) { System.out.println("ERROR: " + error); return; } // Run the MP3 player in new thread to play in the background new Thread() { public void run() { try { player.play(); // Since these next lines are located in the same thread // where the MP3 is playing, they will not execute until // the MP3 has FINISHED playing player.close(); System.out.println("The MP3 has stopped playing."); } catch (Exception error) { System.out.println("ERROR: " + error); } } }.start(); } }