alex suhaiö
alex suhaiö

Reputation: 139

Mediaplayer in JAR

This code compile in Intellij, but it does not work in jar. Working with getResourceAsStream() or getResource doest not solve the problem.

(I have tried out with Image like Image image = newImage(getClass().getResourceAsStream("image.png");and it does work)

package Sound;

import javafx.application.Application;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.io.File;

/**
 */
public class TestSound extends Application{

    public TestSound() {
        play();
    }
    @Override
    public void start(Stage primaryStage) throws Exception {
        new TestSound().play();
    }
    private void play(){
        String mainsound = "src/res/sound/main.mp3";
        Media i = null;
        i = new Media( new File(mainsound).toURI().toString());
        MediaPlayer mediaPlayer = new MediaPlayer(i);
        mediaPlayer.play();
        mediaPlayer.setStopTime(new Duration(120000));
        mediaPlayer.setCycleCount(MediaPlayer.INDEFINITE);
    }
    public static void main (String[] args){
         launch(args);
 }
}

EDIT:

  Media i = new Media(getClass().getClassLoader().getResource(mainsound));

wont work, because the constructor need a String.

but also

  Media i = new     Media(getClass().getClassLoader().getResource(mainsound).toString());
  new MediaPlayer(i).play();

does not work.

ofcourse mainsound="res/sound/main.mp3";

After extraction of jar with winrar I got dictionary of sound with include the testsound.class and main.mp3

And another dictionary of res with include main.mp3

Both dictionary are in the same root.

Upvotes: 0

Views: 1637

Answers (2)

Fahad Ahmad
Fahad Ahmad

Reputation: 1

Instead of using getClass ().getResource (...) it would be ideal to use it like

Media m = new Media ("/myMedia.mp3");//if the media exists in default package

or

Media m = new Media ("/mypackage/myMedia.mp3");//if the media exists in mypackage

Upvotes: 0

James_D
James_D

Reputation: 209704

getClass().getResource("res/sound/main.mp3") is going to look for a resource named res/sound/main.mp3 relative to the current class. Since your class is in the sound package, it's effectively going to look for /sound/res/sound/main.mp3, which is not where the resource is located in your jar.

If the list of entries in the jar file is showing

/sound/main.mp3

then the following should work:

String mediaURL = getClass().getResource("/sound/main.mp3").toExternalForm();
// for debugging:
System.out.println(mediaURL);

Media i = new Media(mediaURL);

Upvotes: 1

Related Questions