JavaFX AudioClip play mp3 file

Description

JavaFX AudioClip play mp3 file


import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.media.AudioClip;
import javafx.stage.Stage;

public class Main extends Application {
  AudioClip audioClip = new AudioClip("http://your.mp3");

  @Override//from  ww w  .  j ava 2s .  c  om
  public void start(Stage primaryStage) {
    Button btPlay = new Button("Play");
    Button btLoop = new Button("Loop");
    Button btStop = new Button("Stop");
    
    HBox hBox = new HBox(5);
    hBox.setAlignment(Pos.CENTER);
    hBox.getChildren().addAll(btPlay, btLoop, btStop);
    
    btPlay.setOnAction(e -> {
      audioClip.setCycleCount(1);
      audioClip.play();
    });

    btLoop.setOnAction(e -> {
      audioClip.setCycleCount(Timeline.INDEFINITE);
      audioClip.play();
    });

    btStop.setOnAction(e -> {
      audioClip.stop();
    });
        

    Scene scene = new Scene(hBox, 200, 100);
    primaryStage.setTitle("java2s.com");
    primaryStage.setScene(scene);
    primaryStage.show();
  }


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



PreviousNext

Related