FXPlayer
JAVAFX MEDIA AND MEDIAPLAYER
In this
post am going to build a simple mp3 player, the functions are few just drag and
drop an mp3 file and it will start playing.
The media
and MediaPlayer class are easy to use, the media class takes care of the source
and the MediaPlayer takes care of the controls.
Let’s first
see what our mp3 looks like,
Playing the MP3
Media
media = new Media(new File("song.mp3"));//file retrieved by drag and
drop event
MediaPlayer
mp=new MediaPlayer(media);
mp.play();
//
scene.setOnDragDropped(new
EventHandler<DragEvent>() {
@Override
public void handle(DragEvent event) {
Dragboard db = event.getDragboard();
boolean success = false;
if(db.hasFiles()){
success=true;
file=db.getFiles().get(0);
if(file.isFile() &&
file.getName().endsWith(".mp3")){
media=new
Media(file.toURI().toString());
mp=new
MediaPlayer(media);
mp.play();
}
}
event.setDropCompleted(success);
event.consume();
}
Volume Slider
This method sets the mediaplayer volume.//i
dont recommend using this method as it is cause is not cheking if the mediaplay
is null or not when adjusting the volume.Which will result in a
NullPointerException.
mp.setVolume(double);
slide.valueProperty().addListener(new ChangeListener<Number>(){
@Override
public void changed(ObservableValue<? extends Number> observable,
Number oldValue, Number newValue) {
mp.setVolume(newValue.doubleValue());
}
});
The Play Button
It checks for the mediaplayer status if status
is playing then pause,else if its paused play.
The variable status keeps track of the
mediaplayer status.
Status status;
initilize the status in drag and drop if its
an mp3 file.
mp.setOnPlaying(new Runnable(){
@Override
public void run() {
status=mp.getStatus();//Status.PLAYING
}
});
play button
play.setOnAction(new EventHandler<ActionEvent>(){
@Override
public void handle(ActionEvent event) {
if(status==Status.PLAYING){
mp.pause();
play.setText("||");
t.setText("Paused");
mp.setOnPaused(new Runnable(){
@Override
public void run() {
status=mp.getStatus();//Status.PAUSED
}
});
}else if(status==Status.PAUSED){
mp.play();
play.setText("I>");
t.setText(file.getName());
mp.setOnPlaying(new Runnable(){
@Override
public void run() {
status=mp.getStatus();//Status.PLAYING
}
});
}
}
});
FUNCTIONS
No song loaded
Playing
Paused
Video Demo
Comments
Post a Comment