10

I have spent hours today looking up how to get some form of audio in eclipse and have had trouble every step of the way. Currently I have something that should work but I get an error:

Exception in thread "main" java.lang.IllegalArgumentException: expected file name as argument at com.sun.javafx.css.parser.Css2Bin.main(Css2Bin.java:44)

I have basically copied this from someone who had it working. I would like to say that the FX lib is added where it should be. I know this isn't fancy but I was just trying the basics.

package b;
import java.io.File;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
public class test {

    public static void main(String[] args){
    String uriString = new File("C:\\Users\\Mike\\workspace\\b\\src\\hero.mp3").toURI().toString()
    MediaPlayer player = new MediaPlayer( new Media(uriString));
    player.play();
}}

I have also tried many different path names in case it was wrong with no luck, I also just tried to copy and paste the path name that i got in eclipse by going to properties ex: /b/src/hero.mp3. Help would be appreciated to get me out of this nightmare.

Kasarrah
  • 315
  • 2
  • 4
  • 14
  • try changing `new Media(uriString)` to `new Media("C:\\Users\\Mike\\workspace\\b\\src\\hero.mp3");` – jmj Jun 22 '14 at 02:42
  • Same error, also the first line becomes unused. – Kasarrah Jun 22 '14 at 02:50
  • Use Test.class.getResource("hero.mp3").toString(); Also, I dint then Eclipse likes resources to be stored in the src directory, they should be stored in the resources directory, as I understand it – MadProgrammer Jun 22 '14 at 02:55
  • Do I assign that to the uristring? Also I am also trying to path from my music libary in windows C:\\Users\\Mike\\Music\\hero.mp3 – Kasarrah Jun 22 '14 at 03:03
  • Yes, `String uriString = Test.class.getResource("/hero.mp3").toString();`. In the case of the file reference you can simply use `String uriString = new File("C:\\Users\\Mike\\Music\\hero.mp3").toURI().toURL().toString()` – MadProgrammer Jun 22 '14 at 03:11

7 Answers7

3

The files located outside the workspace should be included with file:// prefix. A simple example demonstrating the functionality is

public class Reproductor extends Application {

    public static void main(String[] args) {
        launch(args); 
    }

   @Override
   public void start(Stage stage) throws Exception {
       Media media = new Media("file:///Movies/test.mp3"); //replace /Movies/test.mp3 with your file
       MediaPlayer player = new MediaPlayer(media); 
       player.play();
   }  
 }
ItachiUchiha
  • 36,135
  • 10
  • 122
  • 176
2

If the file is into the resources/music this will work and the application will be portable,.mp3 inside the .jar:

Media media = null;
try {
  media = new Media(getClass().getResource("/music/hero.mp3").toURI().toString());
} catch (URISyntaxException e) {
  e.printStackTrace();
} 

enter image description here

GOXR3PLUS
  • 6,877
  • 9
  • 44
  • 93
1

I suspect you have a issue with referencing embedded resources. An embedded resource is any file which is contained within the application context (ie. In this case, stored within the application Jar).

In order to obtain a reference to these resources, you need to use Class#getResource, which returns a URL, which you can then use to load the resource depending on your requirements, for example...

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        String path = Test.class.getResource("/Kalimba.mp3").toString();
        Media media = new Media(path);
        MediaPlayer mp = new MediaPlayer(media);
        mp.play();

        System.out.println("Playing...");
    }

    public static void main(String[] args) {
        launch(args);
    }

}

Now, I couldn't get it to work until I wrapped in a Application context...

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Same error: Exception in thread "main" java.lang.IllegalArgumentException: expected file name as argument at com.sun.javafx.css.parser.Css2Bin.main(Css2Bin.java:44) Maybe its a path error? Or maybe I should uninstall everything and do it clean? – Kasarrah Jun 22 '14 at 03:15
  • Did you use `/hero.mp3` instead of `/Kalimba.mp3`? – MadProgrammer Jun 22 '14 at 03:20
  • Yep and to the above comment new File("C:\\Users\\Mike\\Music\\hero.mp3").toURI().toURL().toString() makes me either do a throw or try/catch – Kasarrah Jun 22 '14 at 03:23
  • Use, `toURL` will throw an `MalformedURLException`, that's what it does. I can verify both versions. It might be that when you build the project, the mp3 is not been included in the resulting Jar because Eclipse doesn't include anything from the `src` directory, but instead uses the contents of the `resources` directory instead – MadProgrammer Jun 22 '14 at 03:28
  • @user3732441 `toURI` is system dependent and most likely doesn't confirm to the RFC-2396 requirements that `Media` is expecting – MadProgrammer Jun 22 '14 at 03:39
1

JavaFX EMBED an MP3 into the jar (in the jar) with NetBeans

I programmed my very first JavaFX package in NetBeans, and then I wanted to add sound, an mp3 music file, embedded in the jar, inside the jar, so that I could email the jar to my friends and the music would play on their computers. Thank you StackOverflow for your help. Thanks especially to the member who said “put your music file IN THE JAR, getResourceAsStream() is the API you want to use.” He put me on the right track, although I ended up using getResource(). It works.

STEP 1: Firstly, I got the music to play when I hit run in NetBeans.

STEP 2: I wanted the music to loop (repeat). Eventually I got that right, thanks to the members of StackOverflow. Please see my source code.

STEP 3: Finally I got the mp3 to EMBED in the jar. Now, this is important. At first the music played on my computer, but the jar read it off my hard disc. When I changed the name of the mp3, then the jar crashed, it would not run, it could not find the mp3. I had to embed the mp3 into the jar, put it inside the jar (in the jar) otherwise it would not play on somebody else’s computer. That’s where getResource() did the trick.

STEP 4: Then I emailed my jar to friends. Some service providers don’t trust a jar, they sent the emails back to me, undelivered. Other service providers don’t have a problem and delivered the emails. So, what did I do? I changed the name of the *.jar to *.mp4 and the emails were delivered, I asked my friends to change it back from *.mp4 to *.jar. It worked.

Here is my source code. I’m sure it’s not perfect, but it works, thanks to StackOverflow.

 /* Of course, one needs to import the following gizmo’s (and others): */
    import javafx.util.Duration;  
    import javafx.scene.media.Media;  
    import javafx.scene.media.MediaPlayer; 
    
    /* I want to EMBED the music inside the jar (in the jar).
     The secret seems to be getResource. The source code starts here,
     to EMBED the sound (DollyParton.mp3) into the jar: */
    
//************************ begin the music ***********************

    @Override public void start(Stage primaryStage) throws Exception {
        init(primaryStage);
        primaryStage.show();
        play();
    }

    public static void main(String[] args) {
        launch(args);
    }
        MediaPlayer musicplayer; {
     
    /* Put your music file IN THE JAR, "getResourceAsStream()" is
    the API you want to use. Put the DollyParton.mp3 into the Windows
    folder src/rockymountain. NetBeans automatically copies the mp3
    to the folder build/classes/rockymountain. */

        Media mp3MusicFile = new Media(getClass().getResource("DollyParton.mp3").toExternalForm()); 
        
        musicplayer = new MediaPlayer(mp3MusicFile);
        musicplayer.setAutoPlay(true);
        musicplayer.setVolume(0.9);   // from 0 to 1      
  
        //***************** loop (repeat) the music  ******************
        musicplayer.setOnEndOfMedia(new Runnable() {    
        public void run() {
        musicplayer.seek(Duration.ZERO); 
       }
         });  
      //*************** end of loop (repeat) the music  **************
        
    }

//**************************** end of music *************************

I put the mp3 into the Windows folder src/rockymountain. Then NetBeans automatically copied the mp3 to the folder build/classes/rockymountain. NetBeans does not copy the mp3 to the folder /resources, a file that I created unnecessarily, because someone said so. The /resources folder is not needed, it remains empty.

Create a Java ARchive (jar) file using NetBeans as follows:

  1. Right-click on the Project name

  2. Select Properties

  3. Click Packaging

  4. Check Build JAR after Compiling

  5. Check Compress JAR File

  6. Click OK to accept changes

  7. Right-click on the Project name

  8. Select Clean and Build

    The JAR file is built. To view it inside NetBeans:

  9. Click the Files tab

  10. Expand ProjectName >> dist (distribution). The jar file is inside the dist folder.

Community
  • 1
  • 1
dirk
  • 61
  • 4
0

Try to add --add-modules=javafx.controls,javafx.media in your VM options.

0

I tried this three lines and it worked!

   Media sound = new Media(new File("src/music/menu.mp3").toURI().toString());
   MediaPlayer player = new MediaPlayer(sound);
   player.play();
Aitsuken
  • 126
  • 10
-1

First you need to put the code in try and catch to catch any error, second you must define the JFXPanel to define it to the media package and the tool kit ,so this is the code:

package test1;

import java.io.File;
import javafx.scene.media.Media;
import javax.swing.JOptionPane;
import javafx.scene.media.MediaPlayer;
import javafx.embed.swing.JFXPanel;

public static void main(String[] args) {

    try {
        JFXPanel j = new JFXPanel();
        String uriString = new File(""C:\\Users\\Mike\\workspace\\b\\src\\hero.mp3"").toURI().toString();
        MediaPlayer Player = new MediaPlayer(new Media(uriString));
        Player.play();

    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, ex);
    }
}

and a good info for you can put only file name inside the File() exp: String uri = new File("hero.mp3").toURI().toString();

  • The OP was using JavaFX, not swing. This question is also 6 years old and has multiple other answers that already solve the problem – NotZack Nov 16 '20 at 23:01
  • Your answer does not bring anything new to this (old) question. Also, as made evident by [your question here](https://stackoverflow.com/questions/64878867/playing-mp3-audio-in-java-is-cutting-off-after-seconds), the code you posted doesn't even work properly. – Patrick Nov 17 '20 at 16:20