What Gradle did is completely expected. The src/main/java and src/main/resources directories store code and resources respectively. The resources folder contains all the non-java code like images,sound etc.
When creating the jar file, the contents of the resources directory will be copied as is (maintaining the package structure). Note that click.mp3 and bgm.mp3 are members of the sound package.
So, when you want to load a resource, it should (generally) not be done using file paths. Instead use, package structure to do so. Here, as the sounds and SoundPlayer
have the same package, i.e. sound
, you can use the SoundPlayer
class to load resources like following:
public SoundPlayer(String filename) {
URL resource = SoundPlayer.class.getResource(filename);
Media soundMedia = new Media(resource.toExternalForm());
mediaPlayer = new MediaPlayer(soundMedia);
}
From Javadocs
public String toExternalForm()
Constructs a string representation of this URL. The string is created by calling the toExternalForm method of the stream protocol handler for this object.
In essence, the toExternalForm() function creates the appropriate URL for a given resource.
Here is a complete example.
// build.gradle
apply plugin: 'java'
apply plugin: 'application'
sourceCompatibility = '1.8'
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
mainClassName = 'sound.Main'
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.10'
}
jar { manifest { attributes 'Main-Class': 'sound.Main' } }
and the modified SoundPlayer
//sound.SoundPlayer
package sound;
import java.net.URL;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
public class SoundPlayer {
private MediaPlayer mediaPlayer;
public SoundPlayer(String filename) {
URL resource = SoundPlayer.class.getResource(filename);
Media soundMedia = new Media(resource.toExternalForm());
mediaPlayer = new MediaPlayer(soundMedia);
}
public void play(){
mediaPlayer.play();
}
}
and the Main class to use SoundPlayer
// sound.Main
// This class does not actually create a JavaFX UI. Instead, it is
// only creating a JavaFX application to use Media
package sound;
import javafx.application.Application;
import javafx.stage.Stage;
/**
*
* @author aga53
*/
public class Main extends Application{
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
SoundPlayer s = new SoundPlayer("test.mp3");
System.out.println("Hello World");
s.play();
}
}