无法在jar文件中读取mp3。 (getResourceAsStream和MediaPlayer)

时间:2015-03-04 23:47:16

标签: multithreading jar mp3 javafx-8 executable-jar

当我将项目导出到.jar文件时,应该播放声音的线程无法启动。构造函数中必须存在一些问题,我猜测加载mp3文件有些问题。但是我得不到URISyntaxException

(在eclipse项目中一切正常) 该类存在于SpokenNumbersController

MediaPlayer media[] = new MediaPlayer[10];
private StringBuilder language = new StringBuilder("/PL.");

    public PlayDigits(){
            generatedDigits = new StringBuilder();
            this.thisType = type;


            for(int i = 0; i < 10; ++i){
                StringBuilder directory = new StringBuilder(language.toString());
                switch(i){
                    case 0: directory.append("Zero.mp3");
                        break;
                    case 1: directory.append("One.mp3");
                        break;
                    case 2: directory.append("Two.mp3");
                        break;
                    case 3: directory.append("Three.mp3");
                        break;
                    case 4: directory.append("Four.mp3");
                        break;
                    case 5: directory.append("Five.mp3");
                        break;
                    case 6: directory.append("Six.mp3");
                        break;
                    case 7: directory.append("Seven.mp3");
                        break;
                    case 8: directory.append("Eight.mp3");
                        break;
                    case 9: directory.append("Nine.mp3");
                        break;
                    default: break;     
                }

        //      URL path = getClass().getResource(directory.toString());
//              media[i] = new MediaPlayer(new Media(path.toString()));

                try {
                    media[i] = new MediaPlayer(new Media(Main.class.getResource(directory.toString()).toURI().toString()));
                } catch (URISyntaxException e) {
                    Dialogs.create().title("Error").masthead(null).message("Couldn't load the mp3").showError();
                    e.printStackTrace();
                }
            }

            digitsToFinish = (int) Math.round(sliderCountdown.getValue());
        }

这是我的文件目录:

enter image description here

我发现我需要使用getResourceAsStream(),但是如何使用MediaPlayer呢?

1 个答案:

答案 0 :(得分:0)

我找到了JLayer的解决方案......

String media[] = new String[10];
...
(its a loop as above)
media[i] = directory.toString();
...

InputStream is = getClass().getResourceAsStream(media[iToDigit]);
Player player = new Player(is);

new Thread(new Runnable() { //just to play sound in background not in main thread
    @Override
        public void run() {
            try {
                player.play();
            } catch (JavaLayerException e) {
                // TODO Auto-generated catch block
                    e.printStackTrace();
            }

        }
}).start();

现在导出的jar文件也播放声音。