gpt4 book ai didi

java - 如何为我的媒体播放器创建停止按钮

转载 作者:行者123 更新时间:2023-11-30 05:53:28 25 4
gpt4 key购买 nike

所以我创建了代码,允许我通过浏览计算机上的音乐文件将歌曲添加到我的音乐播放器,然后使用歌曲名称和文件路径创建一个按钮,以便可以播放它。每次您浏览并选择一首歌曲时,都会将一个新的媒体播放器分配给新创建的歌曲按钮,单击该按钮即可播放该歌曲。我想添加一个停止按钮来停止当前播放的歌曲或所有歌曲。

这是我创建歌曲按钮的方法:

  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);
}
}
});

}

因此,在 browserbutton 的最后一位中,我们调用 makeSongButton 来为歌曲创建一个按钮,以便可以播放它,但是每个 makeSongbutton 调用都会创建一个新的媒体播放器,我希望能够创建一个停止所有媒体播放器的停止按钮。 ...

最佳答案

也许有了这个...

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");
}
});

关于java - 如何为我的媒体播放器创建停止按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53547399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com