因此,我创建了代码,使我可以通过浏览计算机上的音乐文件将歌曲添加到音乐播放器中,然后创建一个带有歌曲名称和文件路径的按钮,以便可以播放。每次浏览和选择歌曲时,都会为新创建的歌曲按钮分配一个新的媒体播放器,该按钮在单击时会播放歌曲。我想添加一个停止按钮,该按钮将停止当前正在播放的歌曲或所有歌曲。
这是我创建歌曲按钮的方法:
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());
}
});
}
每次有人拉出下面显示的程序时,当用户单击显示的按钮BrowseButton时,就会调用此函数:
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);
}
}
});
}
因此,在BrowseButton的最后一位中,我们调用makeSongButton来为歌曲创建一个按钮,以便可以播放它,但是每次makeSongbutton调用都会创建一个新的mediaplayer,我希望能够创建一个停止所有mediaPlayers的停止按钮。 ...
答案 0 :(得分:0)
也许与此...
Button btn_stop = new Button("stop it!");
btn_stop.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
mediaPlayer.stop();
System.out.println("Stop Media Player");
}
});