当前位置: 首页 > 知识库问答 >
问题:

Javafx将声音作为对象播放

贝成业
2023-03-14

我在javafx上做一个项目有困难。我试图播放声音使用媒体和媒体播放器,但遇到了路径选择的麻烦。我在IntellijIDEA工作。我决定简化工作,并创建了一个类sounds.java创建对象,需要字符串(路径)和方法,将播放和停止声音。就像我可以点击按钮很多次和声音播放一遍又一遍)

这是我的代码(由于使用新方法后出现错误,我将代码放在注释中)(

    package sample;



import javafx.fxml.FXMLLoader;
import javafx.scene.Group;

import javafx.scene.Parent;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.paint.Color;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;

import java.io.File;
import java.util.concurrent.atomic.AtomicBoolean;

import static javafx.application.Platform.exit;

public class Main extends Application {

    @Override
    public void start(Stage stage) throws Exception{
        Parent faggot = FXMLLoader.load(getClass().getResource("sample.fxml"));
        Font font = Font.font("Times New Roman", FontWeight.BOLD, 48);

        System.out.println("Working Directory = " + System.getProperty("user.dir"));
        String playClick = System.getProperty("user.dir") + "/src/sounds/select.wav";
        String srcMenuMusic = System.getProperty("user.dir") + "/src/sounds/menu.mp3";

        String picture = System.getProperty("user.dir") + "/src/minotaur.png";



/*        Media click = new Media("select.wav");
        Media menuMusic = new Media(new File(srcMenuMusic).toURI().toString());*/


/*        MediaPlayer clickPlayer = new MediaPlayer(click);
        MediaPlayer menuPlay = new MediaPlayer(menuMusic);*/

        Image image = new Image("/sample/minotaur.png");
        ImageView view = new ImageView(image);
        ImageView view1 = new ImageView(image);
        ImageView view2 = new ImageView(image);
        ImageView view3 = new ImageView(image);


        //Buttons for menu
        int x = 0;
        Button bStart = new Button("Start");
        Button bSettings = new Button("Settings");
        Button bAbout = new Button("About");
        Button bExit = new Button("Exit");

        Button bBack = new Button("Back");
        Button bBack2 = new Button("Back");
        Button bSound = new Button("Sound: ON");
        Button bMusic = new Button("Music: ON");

        bStart.setPrefSize(200, 100);
        bExit.setPrefSize(200, 100);
        bSettings.setPrefSize(200, 100);
        bAbout.setPrefSize(200, 100);

        bStart.setLayoutY(x+10);
        x+=120;
        bSettings.setLayoutY(x);
        x+=110;
        bAbout.setLayoutY(x);
        x+=110;
        bExit.setLayoutY(x);


        bBack.setPrefSize(200, 100);
        bBack.setLayoutY(500);
        bBack.setLayoutX(200);

        bBack2.setPrefSize(200, 100);
        bBack2.setLayoutY(500);
        bBack2.setLayoutX(200);


        bSound.setPrefSize(200, 100);
        bSound.setLayoutY(200);
        bSound.setLayoutX(200);
        bMusic.setPrefSize(200, 100);
        bMusic.setLayoutY(200);
        bMusic.setLayoutX(500);


        String strAbout = "Minotaurus - is a not so funny game about mazes and running away from " +
                "minotaur. So far there is not minotaur yet. But I will probably add him on finals. " +
                "For it is a simple maze with almost no difficulties. Enjoy your short  time wasting!";
        Label lAbout = new Label(strAbout);
        //lAbout.setPrefSize(10, 20);
        lAbout.autosize();
        //lAbout.setRotate(270);
        lAbout.setFont(Font.font("Cambria", 32));
        lAbout.setWrapText(true);
        lAbout.setMaxWidth(400);
        lAbout.setLayoutX(20);

        lAbout.setTextFill(Color.web("#ffffff", 0.8));

        Group root = new Group(view,bStart, bExit, bSettings, bAbout);
        Group gRoot = new Group(view1);
        Group sRoot = new Group(view3, bBack2, bSound, bMusic);
        Group aRoot = new Group(view2, bBack, lAbout);
        Scene scene = new Scene(root, 1280, 720, Color.BEIGE);
        //menuPlay.play();

        Scene sGame = new Scene(gRoot, 1280, 720, Color.BEIGE);
        Scene sAbout = new Scene(aRoot, 1280, 720, Color.BEIGE);
        Scene sSettings = new Scene(sRoot, 1280, 720, Color.BEIGE);


        stage.setTitle("Minotaurus");
        stage.setScene(scene);
        stage.show();

        sounds click = new sounds("/sounds/select.wav");
        bStart.setOnAction(actionEvent ->  {
            click.play();
            click.player.setOnEndOfMedia(click::stop);
            //stage.setScene(sGame);
        });

        /*bSettings.setOnAction(actionEvent ->  {
            clickPlayer.play();
            clickPlayer.setOnEndOfMedia(() -> {
                clickPlayer.stop();
            });
            stage.setScene(sSettings);

        });

        bAbout.setOnAction(actionEvent ->  {
            clickPlayer.play();
            clickPlayer.setOnEndOfMedia(() -> {
                clickPlayer.stop();
            });
            stage.setScene(sAbout);
        });

        bExit.setOnAction(actionEvent ->  {
            clickPlayer.play();
            clickPlayer.setOnEndOfMedia(() -> {
                exit();
            });
        });

        //aux buttons
        bBack.setOnAction(actionEvent ->  {
            clickPlayer.play();
            clickPlayer.setOnEndOfMedia(() -> {
                clickPlayer.stop();
            });
            stage.setScene(scene);
        });

        bBack2.setOnAction(actionEvent ->  {
            clickPlayer.play();
            clickPlayer.setOnEndOfMedia(() -> {
                clickPlayer.stop();
            });
            stage.setScene(scene);
        });*/

        //Checking whether sound on or off
        AtomicBoolean isPlayingSound = new AtomicBoolean(true);
        
        bSound.setOnAction(actionEvent ->  {
            click.play();
            click.player.setOnEndOfMedia(() -> {
                click.stop();
            });

            if(!isPlayingSound.get()){
                isPlayingSound.set(true);
                bSound.setText("Sound: ON");
            }else{
                isPlayingSound.set(false);
                bSound.setText("Sound: OFF");
            }

        });
        //Checking whether menu music is playing or not
        AtomicBoolean isPlayingMenu = new AtomicBoolean(true);
        bMusic.setOnAction(actionEvent ->  {
            click.play();
            click.player.setOnEndOfMedia(() -> {
                click.stop();
            });




            /*if(!isPlayingMenu.get()){
                isPlayingMenu.set(true);
                menuPlay.play();
                bMusic.setText("Music: ON");
            }else{
                isPlayingMenu.set(false);
                menuPlay.pause();
                bMusic.setText("Music: OFF");
            }*/


        });


    }


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

这里是班级sounds.java

package sample;

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


public class sounds {

    String fileName;
    public static final MediaPlayer player = new MediaPlayer();
/*    file:///" + System.getProperty("user.dir").replace('\\', '/') + "/*/
    sounds(String fileName){
        this.fileName = fileName;
        Media m = new Media(fileName);
        player = new MediaPlayer(m);
    }
    public void play(){
            player.play();
    }
    public void stop(){
        player.stop();
    }
}

共有1个答案

艾凯捷
2023-03-14

您需要创建一个sounds对象并在代码中使用它。类似下面的内容。请注意对象是如何在start方法之外定义的,以便可以轻松引用:

public class Main extends Application {

    //Keep a reference to your Sound object
    //Note that methods should ALWAYS start with a capital letter "Sounds"
    sounds mySound;

    @Override
    public void start(Stage stage) throws Exception{

        //Create the sound object near the top of your start method
        mySound = new sounds(yourFilePathAndName);

        //....

        bSound.setOnAction(actionEvent ->  {
            mySound.play();
            mySound.player.setOnEndOfMedia(() -> {
                mySound.stop();
            });

            if(!isPlayingSound.get()){
                isPlayingSound.set(true);
                bSound.setText("Sound: ON");
            }else{
                isPlayingSound.set(false);
                bSound.setText("Sound: OFF");
            }

        });
        //....
    }
    //....
}

注意:在sounds类中,以下行不能是静态的,也不应该是最终的,因为您在代码中使用player=new MediaPlayer(m)对其进行了更改 。删除此行:

public static final MediaPlayer player = new MediaPlayer();

相反,请使用以下命令:

public MediaPlayer player;

 类似资料:
  • 我刚刚开始使用JavaFX。我知道它的基本原理。我尝试使用media和mediaplayer类播放一个声音,叫做“sound.mp3”。我正在eclipse中编程,我在src文件夹中有声音文件,与“(默认包)”相同的文件夹。下面是我的代码: 请告诉我我做错了什么。 下面是来自控制台的错误消息:

  • 我正在试着扮演一个角色。wav文件每次按下鼠标时,程序都会正常启动,但当我点击精灵时,我发现一个错误,有人知道是什么问题吗?我正在使用IntelliJ,SDK 15 这是我试图播放声音的部分 我得到这个错误:

  • 播放(播放音效/播放录音)

  • 问题内容: 我正在开发一个包含许多JButton对象的程序,我希望每个对象都对应于其自己的文件。另外,我希望声音能够与其他按钮的声音重叠,但不能与自身重叠(在播放声音时单击按钮将重新启动声音)。 我尝试使用单个Clip对象,但是在完成上述操作时遇到了麻烦。结果,我诉诸于为每个按钮声明一个新的Clip对象,但是我觉得这对我的问题而言是一种效率很低的解决方案。 如何以最有效的方式完成第一段中所述的内容

  • 我正在开发一个具有许多JButton对象的程序,我希望每个对象都对应于自己的文件。另外,我希望声音的工作方式是,它们可以与其他按钮的声音重叠,但它不能与自身重叠(在播放声音时单击按钮将重新启动声音)。 我尝试使用单个Clip对象,但我无法完成上面所述的内容。因此,我不得不为每个按钮声明一个新的Clip对象,但我觉得这对我的问题来说是一个相当低效的解决方案。 我怎样才能以最有效的方式完成我在第一段中

  • 我希望能够播放mp3文件中的声音,我看到了推荐使用JavaFX的帖子。我实现了MediaPlayer并初始化了JFXPanel,在eclipse中,一切都很好。 然而,当我导出到一个可运行的jar,并尝试运行该程序时,我得到以下错误消息:java.lang.NoClassDefFoundError: javafx/场景/媒体/MediaExcture。 我认为这是因为在较新的JRE版本中排除了Ja