MP3
To play an mp3 we need to use code created by others. When people
want to share code, they often compile it and compress it as a library
file (known as JAR file). The JAR file that you need to use is here.
(Open and SAVE IT TO YOUR FOLDER THAT YOU ARE WORKING WITH) We dont include
it as we include as we would just a class (because its compiled).
In BLUEJ - click preferences - Add library and find that jar file.
Have these imports:
import java.io.*;
import javazoom.jl.player.Player;
And in your code add the methods below:
Player player;
public void stopMP3() { if (player != null) player.close(); }
// play the MP3 file to the sound card
public void playMP3(String filename) {
try {
InputStream is = getClass().getClassLoader().getResourceAsStream(filename);
BufferedInputStream bis = new BufferedInputStream(is);
player = new Player(bis);
}
catch (Exception e) {
System.out.println("Problem playing file " + filename);
System.out.println(e);
}
// run in new thread to play in background
new Thread() {
public void run() {
try { player.play(); }
catch (Exception e) { System.out.println(e); }
}
}.start();
}
}
To start playing a song titled songname.mp3 (which is in your working
folder) you would say:
playMP3("songname.mp3");
to stop it
stopMP3();
The code altogether is below:
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import javazoom.jl.player.Player;
public class MP3 {
String filename;
Player player;
public void stopMP3() { if (player != null) player.close(); }
// play the MP3 file to the sound card
public void playMP3(String filename) {
try {
FileInputStream fis = new FileInputStream(filename);
BufferedInputStream bis = new BufferedInputStream(fis);
player = new Player(bis);
}
catch (Exception e) {
System.out.println("Problem playing file " + filename);
System.out.println(e);
}
// run in new thread to play in background
new Thread() {
public void run() {
try { player.play(); }
catch (Exception e) { System.out.println(e); }
}
}.start();
}
}
If the code is in a jar file: (remember you will need to include the required library)
String filename="resources/smb-overworld.mp3";
URL source = getClass().getResource(filename);
URLConnection servletConnection = source.openConnection();
InputStream in = servletConnection.getInputStream();
player = new Player(in);
|