我想从jar文件本身加载一个mp3文件,然后用JLayer播放它。当我尝试这样做时,我得到一个NullPointerException或一个FileNotFoundException。关于如何解决这个问题的任何想法?
//MP3Player.java
package Music;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import javazoom.jl.player.Player;
public class MP3Player extends Thread
{
private String filename;
private Player player;
private Thread mp3Thread;
private boolean playing;
private boolean locked;
// constructor that takes the name of an MP3 file
public MP3Player()
{
this.filename = "";
mp3Thread = null;
playing = true;
locked = true;
}
public void run()
{
while (playing)
play();
}
public void play()
{
if (!locked)
{
if (filename != null && filename != "")
{
try
{
FileInputStream fis = new FileInputStream(filename);
BufferedInputStream bis = new BufferedInputStream(fis);
player = new Player(bis);
mp3Thread = new Thread()
{
public void run()
{ try { player.play(); } catch (Exception e) { System.out.println(e); } }
};
mp3Thread.start();
// mp3Thread.join();
} catch (Exception e) { System.out.println(e); }
}
}
}
public void changeMusic(String newGuy)
{
locked = true;
filename = "";
try
{
if (player != null)
player.close();
mp3Thread = null;
filename = newGuy;
locked = false;
}
catch (Exception e) {}
}
public void close()
{
locked = true;
playing = false;
try
{
if (player != null)
player.close();
if (mp3Thread != null)
mp3Thread = null;
} catch (Exception e) {}
}
// MusicHandler.java
package Music;
import java.io.File;
import javax.swing.*;
public final class MusicHandler {
public MusicHandler() {
}
public void PlayBoundlessMusic() {
try {
String myFile = (getClass().getResource("/Boundless/Twilight.mp3").getPath());
MP3Player player = new MP3Player();
player.changeMusic(myFile);
player.play();
} catch (Exception e) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(null, e);
}
}
private void PlayMusic(File f) {
}
}
答案 0 :(得分:2)
你的MP3就是所谓的嵌入式资源,它不像文件一样(事实上它甚至不能被视为文件)。我们有时将它们视为虚拟文件。
您需要获取嵌入资源的FileInputStream
,而不是尝试使用InputStream
读取文件。
您应该使用getClass().getClassLoader().getResourceAsStream(fileName)
,这将返回InputStream
...
请记住,如果你打开一个流,你就有责任关闭它......
InputStream fis = null;
BufferedInputStream bis = null;
try
{
fis = getClass().getClassLoader().getResourceAsStream(fileName);
bis = new BufferedInputStream(fis);
player = new Player(bis);
mp3Thread = new Thread()
{
public void run()
{ try { player.play(); } catch (Exception e) { System.out.println(e); } }
};
mp3Thread.start();
// mp3Thread.join();
} catch (Exception e) { System.out.println(e); }
} finally {
try {
fis.close();
} catch (Exception e) {}
try {
bis.close();
} catch (Exception e) {}
}
当然,您可以利用Java 7的auto close (or try-with-resources) feature