2013-05-17 66 views
0

我在jar文件中的classpath中遇到问题。有图片
getClass().getResource("picture.png")工作正常。但我需要得到一个mp3文件。
如果我把整个路径放在jar文件的外面,它工作得很好,但是如果我尝试它
没有像getClass().getResource("picture.png")这样的完整路径,它会显示“找不到文件”。 因此,我正在寻找song.mp3路径的解决方案,以便如果构建.jar并在另一台计算机上打开它,该歌曲仍会播放。如何从jar文件中获取mp3的类路径

这是我的代码:

package bgmusic; 

import java.io.*; 

import javax.media.Format; 
import javax.media.Manager; 
import javax.media.MediaLocator; 
import javax.media.Player; 
import javax.media.PlugInManager; 
import javax.media.format.AudioFormat; 

public class Bgmusic { 
    public static void main(String[] args) { 
     Format input1 = new AudioFormat(AudioFormat.MPEGLAYER3); 
     Format input2 = new AudioFormat(AudioFormat.MPEG); 
     Format output = new AudioFormat(AudioFormat.LINEAR); 
     PlugInManager.addPlugIn(
      "com.sun.media.codec.audio.mp3.JavaDecoder", 
      new Format[]{input1, input2}, 
      new Format[]{output}, 
      PlugInManager.CODEC 
     ); 
     try{ 
      Player player = Manager.createPlayer(new MediaLocator(new File("song.mp3").toURI().toURL())); 
      player.start(); 
     } 
     catch(Exception ex){ 
      ex.printStackTrace(); 
     } 
    } 
} 

回答

1

如果该文件是你的罐子里面,你不能使用new File("song.mp3");。该文件希望它在你的普通os路径内,而不是。

要获得文件从罐子中,您需要使用getResource

例子,假设Song.mp3的是在你的JAR文件的根,而不是在一个目录:

URL url = this.getClass().getResource("song.mp3"); 

从内静态方法,你应该能够得到它如下

URL url = BgMusic.class.getResource("song.mp3"); 
+0

当我尝试,我似乎得到一个错误预期 如果我尝试 InputStream是; is = this.getClass()。getResourceAsStream。(“/ song.mp3”); 我怎么把它放在播放器中? – Henk

+0

道歉,你应该在这种情况下使用getResource而不是getResourceAsStream。 getResource返回一个可直接与MediaLocator一起使用的URL – greedybuddha

+0

Im获取非静态变量现在不能从静态上下文中引用: InputStream is; is = this.getClass()。getResource(“/ song.mp3”); – Henk