如何在javafx中向弹出窗口添加声音

时间:2016-03-22 17:32:22

标签: javafx

如何在弹出窗口时添加声音通知?我想添加自定义声音文件,而不是Windows声音。

代码:

public class PopupWindow {

    Rectangle2D primaryScreenBounds = Screen.getPrimary().getVisualBounds();

    public void display(String newCase) throws IOException {

        Stage window = new Stage();
        Image applicationIcon = new Image(getClass().getResourceAsStream("../images/logo.jpg"));
        window.getIcons().add(applicationIcon);
        window.initStyle(StageStyle.UNDECORATED);

        Label txtNotification = new Label("Новых заявок:");
        Label notification = new Label(newCase);
        notification.setTranslateX(120);
        notification.setStyle("-fx-text-fill: crimson");
        Button closeButton = new Button("x");
        closeButton.setTranslateX(205);
        closeButton.setTranslateY(5);
        closeButton.setOnAction(event -> window.close());

        Pane layout = new Pane();

        layout.getChildren().addAll(txtNotification, notification, closeButton);

        window.setX(primaryScreenBounds.getMinX() + primaryScreenBounds.getWidth() - 245);
        window.setY(primaryScreenBounds.getMinY() + primaryScreenBounds.getHeight() / 1.2);

        Scene scene = new Scene(layout);
        window.setScene(scene);
        layout.getStylesheets().add(this.getClass().getResource("../style/popup.css").toExternalForm());

        window.setAlwaysOnTop(true);
        window.showAndWait();
    }
}

1 个答案:

答案 0 :(得分:1)

在弹出窗口中调用showAndWait()之前播放AudioClip

AudioClip plonkSound = new AudioClip("http://somehost/path/plonk.aiff");
plonkSound.play();

如果要从类路径加载音频剪辑(例如从兄弟位置的jar文件加载到PopopWindow.class),则将剪辑作为资源:

AudioClip plonkSound = new AudioClip(
    PopupWindow.getResource("plonk.aiff").toExternalForm()
);
相关问题