【发布时间】:2015-09-05 08:48:25
【问题描述】:
我正在使用 320 kbps 大约 1 小时长的 MP3 文件。我正在进行的项目将在 MP3 文件中寻找音乐集合,以便它可以随机播放歌曲。我会给程序提供时间戳,它会寻找歌曲。如果 JavaFX 的 seek 方法不是很不准确,它会起作用。
使用MediaPlayer.seek(duration) The MediaPlayer.getCurrentTime() 后,我们按预期返回了我们寻求的持续时间。但是,如果我们收听 mp3 文件(无需搜索或在外部 mp3 播放器中),我们就会意识到报告的时间和实际情况大不相同,有时甚至是几秒钟。
例如MediaPlayer.seek(Duration.millis(2000)) 搜索结果为 0 秒。 2 秒的故障率是不可接受的。
使用 WAV 似乎可以工作。虽然它没有 MP3。
到目前为止,我认为两种解决方法都是可行的:
- 编写没有错误的 MP3 解码器和播放器
- 使用未压缩的 WAV 文件
有没有人知道的更好?
如果有人需要源代码,里面没有更多内容:
public static void main(String[] args) {
MediaPlayer player = null;
JFXPanel fxPanel = new JFXPanel(); //To initialize JavaFX
try {
String url = new File("E:\\Music\\test.mp3").toURI().toURL().toExternalForm();
player = new MediaPlayer(new Media(url));
System.out.println("File loaded!");
} catch (MalformedURLException e) {
//e.printStackTrace();
System.out.println("Error with filename!");
System.exit(0);
}
player.play();
System.out.println("Playing!");
while (true)
{
Scanner reader = new Scanner(System.in);
String string = reader.nextLine();
if (string.equals("Exit")) System.exit(0);
else if (string.equals("Seek"))
{
player.seek(Duration.millis(2000)); //this seeks to the beggining of the file
player.pause();
try {
Thread.sleep(100); //player.getCurrentTime() doesn't update immediately
} catch (InterruptedException e) { }
System.out.println("Time: " + player.getCurrentTime().toMillis() + " / " + player.getTotalDuration().toMillis());
player.play();
}
}
}
【问题讨论】:
-
JavaFX does not support OGG,所以我不确定你为什么在你的问题中引用它。
-
JavaFX 是为用户应用程序代码维护一个single-threaded programming model,您可能应该重写您的测试程序以确保对 JavaFX 媒体系统的所有 API 调用(读取或写入)都在 JavaFX 应用程序上执行线程(请参阅
Platform.runLater()或仅使用Application)。这样做时,请注意不要停止或休眠 JavaFX 应用程序线程。