我正在尝试从下载的文件中获取要在 JavaFX 的 MediaPlayer 上播放的 mp3 文件。这真的很奇怪,因为当我运行代码时,我点击了播放按钮,它只播放了一秒钟。当我按下快退按钮时,MP3 就会播放。我不确定我是否做错了什么。
我尝试使用获取 mp3 的 URL,但收到一条错误消息,指出不支持 https 协议(protocol)。
这是我的代码:
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Files;
import java.net.URL;
import java.io.InputStream;
import java.nio.file.StandardCopyOption;
import static java.nio.file.Files.createTempFile;
public class JavaFXApplet extends Application{
//private static final String MEDIA_URL = "https://www.bensound.com/bensound-music/bensound-summer.mp3";
@Override
public void start(Stage primaryStage) {
Media media = new Media("file:///Users/mycomputer/Downloads/bensound-summer.mp3");
//Media media = new Media(MEDIA_URL);
MediaPlayer mediaPlayer = new MediaPlayer(media);
MediaView mediaView = new MediaView(mediaPlayer);
Button playButton = new Button(">");
playButton.setOnAction(e -> {mediaPlayer.play();});
Button pauseButton = new Button("||");
pauseButton.setOnAction(e-> mediaPlayer.pause());
Button rewindButton = new Button("<<");
rewindButton.setOnAction(e -> mediaPlayer.seek(Duration.ZERO));
Slider slVolume = new Slider();
slVolume.setPrefWidth(150);
slVolume.setMaxWidth(Region.USE_PREF_SIZE);
slVolume.setMinWidth(30);
slVolume.setValue(50);
mediaPlayer.volumeProperty().divide(100);
HBox hBox = new HBox(10);
hBox.setAlignment(Pos.CENTER);
hBox.getChildren().addAll(playButton, pauseButton, rewindButton, new Label("Volume"), slVolume);
BorderPane pane = new BorderPane();
pane.setCenter(mediaView);
pane.setBottom(hBox);
Scene scene = new Scene(pane, 650, 500);
primaryStage.setTitle("Test Player");
primaryStage.setScene(scene);
primaryStage.show();
primaryStage.setOnCloseRequest(windowEvent -> {
mediaPlayer.stop();
});
}
public static void main(String[] args) {
launch(args);
}
}
我正在使用带有 IntelliJ 的 Mac,并且我也尝试过使用 Eclipse,但没有成功。
我愿意接受有关如何使其正常工作或如何使 URL 工作的任何建议。
最佳答案
所以经过一些研究,我最终自己解决了这个问题。
我发现这个 JDK bug 帖子听起来就像我的问题:https://bugs.openjdk.java.net/browse/JDK-8138754
我最终所做的是将其添加到我的代码中以使我的媒体播放器正常工作: mediaPlayer.setCycleCount(MediaPlayer.INDEFINITE);
我希望有一天这能帮助遇到同样问题的人。
关于JavaFX 媒体播放器仅播放一秒的 MP3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59053657/