简体   繁体   English

如何制作非相对JavaFx“媒体”

[英]How to make non-relative JavaFx 'Media'

Whenever I try to convert a File to a JavaFx Media , it tries to make the path relative, which I do not want. 每当我尝试将File转换为JavaFx Media ,它都会尝试使路径相对,而这是我所不希望的。 I'm using a Mac. 我正在使用Mac。

This is my code: 这是我的代码:

static String AUDIO_URL_TO_TEST =  "file://Users/Mike/Desktop/calb.mp3";
basicTime.getAudioOutput().setSource(new File(AUDIO_URL_TO_TEST));

I've tried almost everything for AUDIO_URL_TO_TEST, such as: 我已经尝试了AUDIO_URL_TO_TEST的几乎所有内容,例如:

static String AUDIO_URL_TO_TEST =  "file:///Users/Mike/Desktop/calb.mp3";
static String AUDIO_URL_TO_TEST =  "file:/c:/Users/Mike/Desktop/calb.mp3";
static String AUDIO_URL_TO_TEST =  "/Users/Mike/Desktop/calb.mp3";
static String AUDIO_URL_TO_TEST =  "~/Users/Mike/Desktop/calb.mp3";

This is the code that setSource() calls: 这是setSource()调用的代码:

Media m = new Media(source.getAbsoluteFile().toURI().toURL().toString());
player = new MediaPlayer(m);

Media ends up as something like this: /path/to/eclipse/directory/file://Users/Mike/Desktop/Calb.mp3 , trying to make it relative. 媒体最终像这样: /path/to/eclipse/directory/file://Users/Mike/Desktop/Calb.mp3 to /path/to/eclipse/directory/file://Users/Mike/Desktop/Calb.mp3 : /path/to/eclipse/directory/file://Users/Mike/Desktop/Calb.mp3 ,试图使其相对。

I've tried things other than source.getAbsoluteFile().toURI().toURL().toString() , with just as little luck. 我已经尝试了除source.getAbsoluteFile().toURI().toURL().toString()之外的其他事情,运气还很小。

A side question: Why does the Media class only accept strings? 附带问题:为什么Media类仅接受字符串? That seems like a horrible design. 这似乎是一个可怕的设计。 Strings were meant to contain text, not reference files. 字符串应包含文本,而不是参考文件。

The API doc of Media says: Media的API文档说:

The Media class represents a media resource. Media类代表媒体资源。 It is instantiated from the string form of a source URI. 它是从源URI的字符串形式实例化的。 ... ...

So the constructor of it converts the String path to URI. 因此,它的构造函数将String路径转换为URI。 But since none of the example paths in your question is a valid URI, Media treated them as relative paths. 但是由于问题中的示例路径都不是有效的URI,因此Media会将其视为相对路径。 For more info please refer to File , URI and file protocol documentations. 有关更多信息,请参考FileURI和文件协议文档。 The valid URI can be: 有效的URI可以是:

File f = new File("C:/Users/Mike/Desktop/Calb.mp3");
Media m = new Media(f.toURI().toString());

Alternatively, 或者,

URI uri = new URI("file:///C:/Users/Mike/Desktop/Calb.mp3");
// or
URI uri = new URI("file:/C:/Users/Mike/Desktop/Calb.mp3");
// in short.
Media m = new Media(uri.toString());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM