JavaFX MediaPlayer play mp3 file
import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Application; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.scene.layout.StackPane; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.scene.text.Font; import javafx.stage.Stage; import javafx.util.Duration; public class Main extends Application { protected TextField count = new TextField(); protected Media media = new Media("your.mp3"); protected MediaPlayer mediaPlayer = new MediaPlayer(media); protected Timeline animation; @Override//w ww . ja va 2s . c o m public void start(Stage primaryStage) { // Set text field properties count.setAlignment(Pos.CENTER); count.setFont(Font.font(60)); count.setPrefColumnCount(4); mediaPlayer.setCycleCount(MediaPlayer.INDEFINITE); // Create a pane StackPane pane = new StackPane(count); // Create animation for stopwatch animation = new Timeline(new KeyFrame(Duration.millis(1000), e -> run())); animation.setCycleCount(Timeline.INDEFINITE); count.setOnKeyPressed(e -> { if (e.getCode() == KeyCode.ENTER) { animation.play(); } }); // Create a scene and place it in the stage Scene scene = new Scene(pane); primaryStage.setTitle("java2s.com"); primaryStage.setScene(scene); primaryStage.show(); } /* Animate the stopwatch and controls mediaPlayer */ private void run() { if (Integer.parseInt(count.getText()) > 0) { mediaPlayer.pause(); mediaPlayer.seek(Duration.ZERO); count.setText(String.valueOf(Integer.parseInt(count.getText()) - 1)); } if (count.getText().equals("0")) { animation.pause(); mediaPlayer.play(); } } }