【发布时间】:2014-12-30 05:07:10
【问题描述】:
我目前正在开发一个在单击按钮时将播放某些歌曲的项目。 我现在让我的代码正常工作,以便它正确播放 mp3 文件,但这不是我想要的方式。现在我只是从我的桌面引用 mp3 文件,但我希望能够从项目本身引用它。我创建了一个名为 resources 的源文件夹,并且在其中有一个名为 music 的文件夹,我将 mp3 文件放入其中。不过,我在弄清楚如何正确引用 mp3 文件时遇到了麻烦。
这是我当前在桌面上播放歌曲的代码:
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();
}
}
【问题讨论】: