Search code examples
javaaudiojavafxplayback

Playing sound files with Java - Error: Could not find or load main class [Classname]


I'm trying to (do something as 'simple' as) getting java to play a sound file. I've got the following java-code for it:

import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;

public class HelloWorldSound

{
    public static void main(String args[]) throws Exception {
        String soundFile = "sound.mp3";
        Media hit = new Media(soundFile);
        MediaPlayer mediaPlayer = new MediaPlayer(hit);
        mediaPlayer.play();
    }
}

(Sound file is in the same directory as the .java and .class file)

I compile it using:

    javac -cp jfxrt.jar HelloWorldSound

(The .jar file is in the same folder)

No errors on compilation, but when i try to run it with:

    java -cp jfxrt.jar HelloWorldSound

I get the follwing error:

    Error: Could not find or load main class HelloWorldSound

I'm running java version "1.7.0_45"

Any help on where i made my mistake(s)?

The overall idea: The program is for a project, where input from an arduino will decide which sound to play and how often it should be repeated. If there is a better way to playback sound, please let me know :)


Solution

  • If you run it like this:

    java -cp jfxrt.jar HelloWorldSound
    

    then the only thing that is in your classpath is jfxrt.jar. If your class HelloWorldSound is not in a package and your have HelloWorldSound.class in your current directory, then you need to put the current directory in the classpath too:

    java -cp jfxrt.jar;. HelloWorldSound
    

    Note: . indicates the current directory.