so I have code created allowing me to add songs to my music player by browsing music files on your computer and then a button is created with the song name and file path so it can be played. Each time you browse and pick a song a new mediaplayer is a assigned to the newly created song button which plays the song when clicked. I want to add a stop button that will stop either the currently playing song or all songs.
here is how I create song buttons:
public void makeSongButton(Song song) {
MyButton myButton = new MyButton(song, "Play " + song.getName() + " (" +
song.getDuration() + ")", this.nextX, this.nextY);
//update nextY
this.nextY++;
// add to buttons list
this.buttons.add(myButton);
myButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//code to play a song modified from stackoverflow user jasonwaste's answer on https://stackoverflow.com/questions/6045384/playing-mp3-and-wav-in-java
//system.out.println("play!!!");
labelError.setText("play!");
final MyButton myButton = (MyButton)event.getSource();
final Song song = myButton.getSong();
String songFile = song.getFile();
Media media = new Media(new File(songFile).toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();
//update player state...
labelMsg.setText(song.getName());
}
});
}
This function is called when someone clicks on the button BrowseButton that shows up everytime you pull up the program shown bellow:
public void makeBrowseButton(Stage primaryStage, BMPData bmpData) {
browseButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
labelError.setText("browse!");
// create fileChooser so user can browse
FileChooser fileChooser = new FileChooser(); // create object
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Audio Files", "*.wav", "*.mp3", "*.aac")); //filter for music files
if ( !parentPath.equalsIgnoreCase("")) { //go to previous directory if exists
File parentPathFile = new File(parentPath);
fileChooser.setInitialDirectory(parentPathFile);
}
File selectedFile = fileChooser.showOpenDialog(primaryStage); // display the dialog box
// processing IF file was chosen
if (selectedFile != null) {
// extract song name and file name from selected file object
String name = selectedFile.getName();
String wholePath = selectedFile.getPath();
parentPath = selectedFile.getParent();
Song song = new Song(name, wholePath);
//update library
bmpData.setNewSong(song);
//make a button for the song
makeSongButton(song);
createDisplay(primaryStage, bmpData);
}
}
});
}
So in the last bit of browsebutton we call makeSongButton that creates a button for the song so it can be played, but each makeSongbutton call creates a new mediaplayer and I want to be able to create a stop button that stops all mediaPlayers....