我想使用javaFX一个接一个地播放5个声音文件。我努力连续打两场比赛。此代码仅播放前两个声音文件,然后播放第三个声音文件。我希望能够播放多达5个声音文件,但没有限制将是理想的。任何帮助表示赞赏。谢谢! 我试着制作一个会说话的时钟,告诉你时间,而我却被困在你可以说话的那一部分上。
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
public class MediaFX extends Application{
MediaPlayer mediaplayer;
public static void main(String[] args){
launch(args);
}
@Override
public void start(Stage stage){
Media hello = new Media("file:///C:/Users/Good/Desktop/TimeFiles/one.wav");
Media meow = new Media("file:///C:/Users/Good/Desktop/TimeFiles/oh.wav");
Media neww = new Media("file:///C:/Users/Good/Desktop/TimeFiles/six.wav");
mediaplayer = new MediaPlayer(hello);
mediaplayer.play();
mediaplayer.setOnEndOfMedia(new Runnable(){
@Override
public void run(){
mediaplayer.stop();
mediaplayer = new MediaPlayer(meow);
mediaplayer.setAutoPlay(false);
mediaplayer.play();
}
});
mediaplayer.setOnEndOfMedia(new Runnable(){
@Override
public void run(){
mediaplayer.stop();
mediaplayer = new MediaPlayer(neww);
mediaplayer.setAutoPlay(false);
mediaplayer.play();
}
});
VBox root = new VBox();
root.getChildren().addAll();
Scene scene = new Scene(root,500,500);
stage.setScene(scene);
stage.show();
}
}
答案 0 :(得分:1)
你必须找到一种方法来创建某些动作的循环,以便能够实现你想要的。你需要:
一种很好的方法是通过递归调用init函数,如下所示:
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
public class MediaFX extends Application {
MediaPlayer mediaplayer;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) {
Media hello = new Media(this.getClass().getResource("one.wav").toExternalForm());
Media meow = new Media(this.getClass().getResource("two.wav").toExternalForm());
Media neww = new Media(this.getClass().getResource("three.wav").toExternalForm());
ObservableList<Media> mediaList = FXCollections.observableArrayList();
mediaList.addAll(hello, meow, neww);
playMediaTracks(mediaList);
VBox root = new VBox();
stage.setScene(new Scene(root,300,300));
stage.show();
}
private void playMediaTracks(ObservableList<Media> mediaList) {
if (mediaList.size() == 0)
return;
MediaPlayer mediaplayer = new MediaPlayer(mediaList.remove(0));
mediaplayer.play();
mediaplayer.setOnEndOfMedia(new Runnable() {
@Override
public void run() {
playMediaTracks(mediaList);
}
});
}
}