1

我正在使用 JLayer MP3 库在我的程序中播放 MP3 文件。

我的老师告诉我们使用类似的东西:

imageLabel = new JLabel(ImageIcon(this.getClass().getResource("filename.jpg")));

如果我们要将程序导出为可执行的 .jar 文件,则加载我们的音乐和图像。但是,当我对音乐执行此操作时,我收到错误消息“构造函数 MP3(URL) 未定义”。

这是我的 Homepage 类的代码部分:

//Play music 
MP3 mp3 = new MP3(this.getClass().getResource("YGSA.mp3"));
mp3.play();

这是 MP3 类的部分代码:

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 String toString() {
return 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();
}

有没有其他方法可以加载音乐以便它可以在 .jar 中工作?其他一切正常。只有音乐在表演。

我已经坚持了一段时间,所以任何建议将不胜感激!

4

1 回答 1

0

尝试使用资源作为流,而不是读取资源 URL。下面是您需要做的一些更改。尝试重构变量名称。

Firt change your call to use getResourceAsStream instead of getResource. Second, Change your MP3 class constructor to receive a InputStream instead of String (also change your fileName variable type to InputStream. Refact their name here.

Finally, change your play method to use the inputStream.

MP3 mp3 = new MP3(this.getClass().getResourceAsStream("YGSA.mp3"));
mp3.play();


 public MP3(InputStream filename) {
   this.filename = filename;

 }
public void play() {
try {
    BufferedInputStream bis = new BufferedInputStream(fis);
    player = new Player(bis);
}
catch (Exception e) {
    System.out.println("Problem playing file " + filename);
    System.out.println(e);
}
于 2013-06-11T02:37:01.357 回答