这是我关于JavaFX的第二个问题。我很抱歉因为我不是一个经验丰富的Java程序员,而且是JavaFX的新手。我不完全理解以前的答案,并会在以后一次又一次地阅读。但现在我有下一个问题。我按如下方式重写了我的程序:
import java.io.FileNotFoundException;
import java.io.IOException;
import static java.lang.Thread.sleep;
import java.util.concurrent.TimeUnit;
import javafx.application.Application;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage; import javafx.util.Duration;
public class JavaFXMediaPlayer05 extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws FileNotFoundException,IOException, InterruptedException {
Media media = new Media("file:///D:/1016_00.mp3");
//Set and play the first fragment of mp3-file
MediaPlayer mediaPlayer1 = new MediaPlayer(media);
mediaPlayer1.setStartTime(Duration.millis(1219.0));
mediaPlayer1.setStopTime(Duration.millis(2728.0));
mediaPlayer1.play();
System.out.println("1st fragment played!");
TimeUnit.SECONDS.sleep(3);
//Set and play the second fragment
MediaPlayer mediaPlayer2 = new MediaPlayer(media);
mediaPlayer2.setStartTime(Duration.millis(3947.0));
mediaPlayer2.setStopTime(Duration.millis(6629.0));
mediaPlayer2.play();
System.out.println("2nd fragment played!");
TimeUnit.SECONDS.sleep(3);
//Set and play the third fragment
MediaPlayer mediaPlayer3 = new MediaPlayer(media);
mediaPlayer3.setStartTime(Duration.millis(7453.0));
mediaPlayer3.setStopTime(Duration.millis(10704.0));
mediaPlayer3.play();
System.out.println("3rd fragment played!");
//Just sleep
System.out.println("pre-sleep");
TimeUnit.SECONDS.sleep(3);
System.out.println("after-sleep");
}
}
我在NetBeans中逐步调试它。我得到一个奇怪的结果。我听到的声音不是在mediaplayer.play(),而是在方法start()的末尾。所有3个片段一次播放。如何管理它们按顺序播放?我是否需要多次触发方法start() - 每个片段一次?或者还有另一种方式吗?
答案 0 :(得分:2)
MediaPlayer
开始异步播放媒体。所以mediaPlayerN.play()
同时发生。
您可以使用Timeline
在特定时间开始播放,请参阅下文。
此外,由于所有播放器只有1个媒体,因此您可以对所有样本使用相同的MediaPlayer
。请注意,在这种情况下,您应该使用seek()
方法而不是setStartTime()
。
final MediaPlayer mediaPlayer1 = new MediaPlayer(media);
Timeline timeline = new Timeline(
new KeyFrame(Duration.ZERO, "plays at start", new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
mediaPlayer1.setStartTime(Duration.millis(1219.0));
mediaPlayer1.setStopTime(Duration.millis(2728.0));
mediaPlayer1.play();
}
}),
new KeyFrame(Duration.seconds(5), "plays after 5 seconds", new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
mediaPlayer1.seek(Duration.millis(3947.0));
mediaPlayer1.setStopTime(Duration.millis(6629.0));
mediaPlayer1.play();
}
}),
new KeyFrame(Duration.seconds(10), "plays after 10 seconds", new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
mediaPlayer1.seek(Duration.millis(7453.0));
mediaPlayer1.setStopTime(Duration.millis(10704.0));
mediaPlayer1.play();
}
})
);
timeline.play();