简体   繁体   English

使用 javafx 获取要播放的 mp3 文件

[英]Getting a mp3 file to play using javafx

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.我今天花了几个小时寻找如何在 eclipse 中获得某种形式的音频,并且在每一步都遇到了麻烦。 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)线程“main”中的异常 java.lang.IllegalArgumentException: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.我想说的是 FX 库被添加到了它应该在的地方。 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.我还尝试了许多不同的路径名,以防万一它不走运,我也只是尝试通过转到属性(例如:/b/src/hero.mp3)来复制和粘贴我在 eclipse 中获得的路径名。 Help would be appreciated to get me out of this nightmare.帮助我摆脱这个噩梦将不胜感激。

The files located outside the workspace should be included with file:// prefix.位于工作区之外的文件应包含file://前缀。 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();
   }  
 }

If the file is into the resources/music this will work and the application will be portable, .mp3 inside the .jar :如果文件在resources/music这将起作用并且应用程序将是可移植的, .mp3 inside the .jar

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

在此处输入图片说明

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).嵌入资源是包含在应用程序上下文中的任何文件(即,在这种情况下,存储在应用程序 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...为了获得对这些资源的引用,您需要使用Class#getResource ,它返回一个URL ,然后您可以根据您的要求使用它来加载资源,例如...

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...现在,我无法让它工作,直到我包装在Application上下文中......

JavaFX EMBED an MP3 into the jar (in the jar) with NetBeans JavaFX 使用 NetBeans 将 MP3 嵌入到 jar(在 jar 中)中

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.我在 NetBeans 中编写了我的第一个 JavaFX 包,然后我想添加声音,一个 mp3 音乐文件,嵌入在罐子里,罐子里,这样我就可以把罐子通过电子邮件发送给我的朋友,音乐就可以在他们的电脑上播放. Thank you StackOverflow for your help.感谢 StackOverflow 的帮助。 Thanks especially to the member who said “put your music file IN THE JAR, getResourceAsStream() is the API you want to use.”特别感谢那位说“把你的音乐文件放在 JAR 中,getResourceAsStream() 是你想要使用的 API”的成员。 He put me on the right track, although I ended up using getResource().他让我走上了正轨,尽管我最终使用了 getResource()。 It works.有用。

STEP 1: Firstly, I got the music to play when I hit run in NetBeans.第 1 步:首先,当我在 NetBeans 中点击运行时,我开始播放音乐。

STEP 2: I wanted the music to loop (repeat).第 2 步:我想让音乐循环播放(重复)。 Eventually I got that right, thanks to the members of StackOverflow.最终我做对了,感谢 StackOverflow 的成员。 Please see my source code.请看我的源代码。

STEP 3: Finally I got the mp3 to EMBED in the jar.第 3 步:最后我将 mp3 嵌入到 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.当我更改mp3的名称时,jar崩溃了,它无法运行,找不到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.我不得不将 mp3 嵌入到罐子中,把它放在罐子里(在罐子里),否则它不会在别人的电脑上播放。 That's where getResource() did the trick.这就是 getResource() 发挥作用的地方。

STEP 4: Then I emailed my jar to friends.第 4 步:然后我将我的罐子通过电子邮件发送给朋友。 Some service providers don't trust a jar, they sent the emails back to me, undelivered.一些服务提供商不信任 jar,他们将电子邮件发回给我,但未送达。 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.我将*.jar 的名称更改为*.mp4 并发送了电子邮件,我让我的朋友将其从*.mp4 更改回*.jar。 It worked.有效。

Here is my source code.这是我的源代码。 I'm sure it's not perfect, but it works, thanks to StackOverflow.我确信它并不完美,但它可以工作,感谢 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.我将 mp3 放入 Windows 文件夹 src/rockymountain。 Then NetBeans automatically copied the mp3 to the folder build/classes/rockymountain.然后 NetBeans 自动将 mp3 复制到文件夹 build/classes/rockymountain。 NetBeans does not copy the mp3 to the folder /resources, a file that I created unnecessarily, because someone said so. NetBeans 不会将 mp3 复制到文件夹 /resources,这是我不必要地创建的文件,因为有人这么说。 The /resources folder is not needed, it remains empty. /resources 文件夹不是必需的,它保持为空。

Create a Java ARchive (jar) file using NetBeans as follows:使用 NetBeans 创建一个 Java 归档 (jar) 文件,如下所示:

  1. Right-click on the Project name右键单击项目名称

  2. Select Properties选择属性

  3. Click Packaging点击包装

  4. Check Build JAR after Compiling编译后检查 Build JAR

  5. Check Compress JAR File检查压缩 JAR 文件

  6. Click OK to accept changes单击确定接受更改

  7. Right-click on the Project name右键单击项目名称

  8. Select Clean and Build选择清理和构建

    The JAR file is built. JAR 文件已构建。 To view it inside NetBeans:要在 NetBeans 中查看它:

  9. Click the Files tab单击文件选项卡

  10. Expand ProjectName >> dist (distribution).展开 ProjectName >> dist(分布)。 The jar file is inside the dist folder. jar 文件位于 dist 文件夹中。

尝试在 VM 选项中添加--add-modules=javafx.controls,javafx.media

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();

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:首先,您需要将代码放入 try 和 catch 中以捕获任何错误,其次您必须定义 JFXPanel 以将其定义到媒体包和工具包中,因此这是代码:

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();一个很好的信息,你可以只把文件名放在 File() exp 中: String uri = new File("hero.mp3").toURI().toString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM