So i'm trying to make a jukebox app using javafx and scenebuilder. It has a keypad in which i type the number of the song into a label, the text on the label is converted to an int and passed to the track() method which picks a track from the array (the array is a placeholder for something fancier in the future) The play() method plays the track just fine... Code of the controller class:
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
public class MainController implements Initializable {
@Override
public void initialize(URL location, ResourceBundle resources) {
// TODO Auto-generated method stub
}
@FXML
private Label number;
public void zero(ActionEvent event){
number.setText(number.getText() + "0");
}
public void one(ActionEvent event){
number.setText(number.getText() + "1");
}
public void two(ActionEvent event){
number.setText(number.getText() + "2");
}
public void three(ActionEvent event){
number.setText(number.getText() + "3");
}
public void four(ActionEvent event){
number.setText(number.getText() + "4");
}
public void five(ActionEvent event){
number.setText(number.getText() + "5");
}
public void six(ActionEvent event){
number.setText(number.getText() + "6");
}
public void seven(ActionEvent event){
number.setText(number.getText() + "7");
}
public void eight(ActionEvent event){
number.setText(number.getText() + "8");
}
public void nine(ActionEvent event){
number.setText(number.getText() + "9");
}
public void clear(){
number.setText("");
}
public MediaPlayer track(){
URL[] songs = new URL[]{
getClass().getResource("/res/03. Eyes On Fire.mp3"),
getClass().getResource("/res/05,Graveyard-Endless Night.mp3"),
getClass().getResource("/res/10 Nas - It Ain't Hard To Tell.mp3")
};
final Media media = new Media(songs[Integer.parseInt(number.getText())].toString());
final MediaPlayer mediaplayer = new MediaPlayer(media);
return mediaplayer;
}
public void play(){
track().play();
}
public void stop(){
track().stop();
}
}
Thanks in advance.
Your track()
method is creating a new MediaPlayer
every time you call it. So when you call stop()
you are calling it on a different instance to the one on which you called play()
, and the one on which you call play()
never gets stopped.
You need to keep a reference to the "current" MediaPlayer
. Let track()
(or perhaps selectTrack()
update that reference, then you can call stop()
on it when you need. Something like:
public class MainController {
private MediaPlayer player ;
// ...
public void selectTrack() {
URL[] songs = new URL[] { ... } ;
final Media media = new Media(songs[Integer.parseInt(number.getText())].toString());
this.player = new MediaPlayer(media);
}
public void play() {
// stop current player:
if (player != null) {
player.stop();
}
selectTrack();
player.play();
}
public void stop() {
player.stop();
}
}