按键53次后声音停止工作

时间:2019-08-04 11:02:04

标签: javafx audio

我正在用JavaFX创建游戏(类似Space Invaders),但是拍摄声音有问题,尤其是当我多次按下某个键时,不仅声音停止播放,其他声音也停止播放工作。

我已经进行了一些小研究,似乎这种问题相当普遍,涉及释放MediaPlayer对象/实例,但我不能调用该方法(?)。

我尝试使用dispose()方法,但是它会完全禁用镜头声音。

我有两个类,GameApp:

primaryStage.getScene().setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                if (event.getCode() == KeyCode.SPACE && playable) {
                    Audio.playPlayerShotSound();
                }
            }
        });

和音频:


public class Audio {

    private static Media shot = new Media(new File("resources/playerShot.wav").toURI().toString());

    public static void playPlayerShotSound() {
        MediaPlayer shotSound = new MediaPlayer(shot);
        shotSound.setVolume(0.2);
        shotSound.play();
    }

我已经使用JavaFX创建了另一个类,按下Space 64次后声音停止了。


package examples;

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
import javafx.scene.layout.Pane;
import java.io.File;

public class GameInst extends Application {

    Pane root;

    private AnimationTimer timer;
    private static Media shot = new Media(new File("resources/playerShot.wav").toURI().toString());
    int count = 0;

    private Parent createContent() {
        root = new Pane();
        root.setPrefSize(500, 500);


        timer = new AnimationTimer() {
            @Override
            public void handle(long now) {
                onUpdate();
            }
        };
        AnimationTimer timer = new AnimationTimer() {
            @Override
            public void handle(long now) {
                onUpdate();
            }
        };
        timer.start();

        return root;
    }

    private void onUpdate() {
    }

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

        root = new Pane();

        primaryStage.setTitle("Space Invaders");
        primaryStage.setScene(new Scene(createContent()));

        primaryStage.getScene().setOnKeyPressed(event -> {
            switch (event.getCode()) {
                case SPACE:
                    MediaPlayer shotSound = new MediaPlayer(shot);
                    shotSound.setVolume(0.1);
                    shotSound.play();
                    count++;
                    System.out.println(count);
            }
        });
        primaryStage.show();
    }

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


1 个答案:

答案 0 :(得分:1)

对于您想要做的事情,AudioClip类可能更适合作为功能强大的MediaPlayer。每当您收到事件时,初始化一个新玩家也是一个好主意。