I am currently working on a project that will play certain songs when buttons are clicked. I now have my code working so that it correctly plays the mp3 file however it is not the way I want to do it. Right now I am just referencing the mp3 file from my desktop but I would like to be able to reference it from the project itself. I created a source folder called resources and I have a folder in there called music that I put the mp3 files in. I'm having trouble figuring out how to correctly reference the mp3 file though.
This is my current code that plays the song off of my desktop:
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import javazoom.jl.player.Player;
public class MP3 {
private String filename;
private Player player;
// constructor that takes the name of an MP3 file
public MP3(String filename) {
this.filename = filename;
}
public void close() {
if (player != null)
player.close();
}
// play the MP3 file to the sound card
public void play() {
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();
}
// test client
public static void main(String[] args) {
String filename = "/Users/username/desktop/LoveStory.mp3";
MP3 mp3 = new MP3(filename);
mp3.play();
// when the computation is done, stop playing it
mp3.close();
// play from the beginning
mp3 = new MP3(filename);
mp3.play();
}
}
Aucun commentaire:
Enregistrer un commentaire