我试图在点击一个按钮时添加一个声音,但它似乎不起作用。我一直在尝试不同的方法,这似乎是最接近的工作,除了这一个错误消息。我愿意接受任何建议。
package beatbox;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.scene.media.AudioClip;
import javafx.stage.Stage;
import sun.audio.AudioPlayer;
public class BeatBox extends Application {
// Adding audio clip
private static final AudioClip clip1 = new AudioClip(AudioPlayer.class.getResource("http://www.wavlist.com/soundfx/029/piano2.wav").toString());
@Override
public void start(Stage primaryStage) {
// Create gridpane for button display
GridPane gridPane = new GridPane();
Button btn1 = new Button("");
gridPane.add(btn1, 0, 0, 1, 1);
// Playing sound and changing color on button click
btn1.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
clip1.play();
btn1.setStyle(" -fx-base: #99ccff;");
}
});
Scene scene = new Scene(gridPane, 302, 335);
primaryStage.setScene(scene);
primaryStage.setResizable(false);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
(UPDATE) 这是例外
Exception in thread "JavaFX Application Thread" Exception in thread "main" java.lang.ExceptionInInitializerError
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplicationWithArgs$156(LauncherImpl.java:352)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException
at beatbox.BeatBox.<clinit>(BeatBox.java:24)
答案 0 :(得分:2)
好的,首先,请用大括号关闭主要方法&#34;}&#34;摆脱语法错误。其次,删除导入:
import sun.audio.AudioPlayer;
并导入:
import javafx.scene.media.AudioClip;
第三步,删除AudioPlayer.class.getResource()。toString并使用网址。
private static final AudioClip clip1 = new AudioClip("http://www.wavlist.com/soundfx/029/piano2.wav");
那就是它。音频播放!