如何使用 JavaFX 播放声音

2022-09-03 03:49:33

我刚刚开始使用JavaFX。我知道它的基本原理。我试图使用媒体和mediaplayer类来播放一种声音,称为“声音.mp3”。我正在用eclipse编程,我在src文件夹中有声音文件,与“(默认包)”文件夹相同。这是我的代码:

import javafx.scene.media.*;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Main extends Application {

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

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Hello World!");

        String ssound = "sound.mp3";
        Media sound = new Media(ssound);
        MediaPlayer mediaPlayer = new MediaPlayer(sound);
        mediaPlayer.play();

        StackPane root = new StackPane();
        primaryStage.setScene(new Scene(root, 800, 450));
        primaryStage.show();
    }
}

请告诉我我做错了什么。

以下是来自控制台的错误消息:

Exception in Application start method
Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown Source)
    at com.sun.javafx.application.LauncherImpl.access$000(Unknown Source)
    at com.sun.javafx.application.LauncherImpl$1.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:724) Caused by: java.lang.IllegalArgumentException: uri.getScheme() == null!
    at com.sun.media.jfxmedia.locator.Locator.<init>(Unknown Source)
    at javafx.scene.media.Media.<init>(Unknown Source)
    at Main.start(Main.java:16)
    at com.sun.javafx.application.LauncherImpl$5.run(Unknown Source)
    at com.sun.javafx.application.PlatformImpl$5.run(Unknown Source)
    at com.sun.javafx.application.PlatformImpl$4$1.run(Unknown Source)
    at com.sun.javafx.application.PlatformImpl$4$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl$4.run(Unknown Source)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.access$100(Unknown Source)
    at com.sun.glass.ui.win.WinApplication$3$1.run(Unknown Source) ... 1 more

答案 1

只是其他答案所说的工作汇编:

String musicFile = "StayTheNight.mp3";     // For example

Media sound = new Media(new File(musicFile).toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(sound);
mediaPlayer.play();

将音乐文件添加到“项目”文件夹中,旁边是 和 。binsrc

任何 IDE 都会提示您添加这些内容:

import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import java.io.File;

像吊饰一样工作。


答案 2
mApplause = new AudioClip(this.getClass().getResource("/sounds/applause.mp3").toExternalForm());

所以这就是我使用的东西,它的工作原理,我知道它可能不再重要了,但是由于它进入了我的谷歌搜索,而我正在寻找其他东西,我想我会回答它。:)

这意味着 toExternal Form 它告诉形成路径文件的 url 形式。


推荐