目前,在 Java FX 中实现此目的的最佳方式是使用嵌入式 HTTP 服务器并使用 HTTP Live Streaming(视频点播)。请参阅此链接以了解 HLS。因此,无论何时您准备好播放视频,在您创建 Media 对象之前...
// Creates a server on localhost, port 7777, runs on background thread
// Note that Media does not recognize localhost, you'll have to use 127.0.0.1
HttpServer httpServer = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 7777), 0);
httpServer.createContext("/", new CustomHttpHandler("/dir/to/files/to/play"));
httpServer.start();
...在您的本地机器上,在您传递给 CustomHttpHandler 的目录中,您需要有一个 .m3u8 文件和用于播放的文件。对于最简单的情况,要播放的文件应该是 .ts 文件,但只要在处理它们的请求时将它们转换为 MPEG-2 TS 格式,它们就可以是任何文件。再来看看CustomHttpHandler...
public class CustomHttpHandler implements HttpHandler {
private String rootDirectory;
public CustomHttpHandler(String rootDirectory) {
this.rootDirectory = rootDirectory;
}
@Override
public void handle(HttpExchange httpExchange) throws IOException {
URI uri = httpExchange.getRequestURI();
File file = new File(rootDirectory + uri.getPath()).getCanonicalFile();
Headers responseHeaders = httpExchange.getResponseHeaders();
if (uri.toString().contains(".ts")) {
responseHeaders.set("Content-Type", "video/MP2T");
} else {
responseHeaders.set("Content-Type", "application/vnd.apple.mpegurl");
}
if (file.exists()) {
byte[] bytes = Files.readAllBytes(Paths.get(file.toURI()));
httpExchange.sendResponseHeaders(200, 0);
OutputStream outputStream = httpExchange.getResponseBody();
outputStream.write(bytes);
outputStream.close();
}
}
}
...请注意,此 HttpHandler 假设您要提供的文件已经是 .ts 格式,但如果您有其他文件(加密数据、压缩数据、MP4、RAW H264、二进制文件等),您需要做的就是将其转换为 .ts 格式并将该数据写入上面的输出流。然后,在您启动并运行此服务器后,您要做的就是创建您的媒体!
// Note the 127.0.0.1 here, localhost will NOT work!
Media myMedia = new Media("http://127.0.0.1:7777/something.m3u8")
...就是这样!现在您有了一个 Java FX 媒体播放器,它可以从任何地方加载并支持完整的播放功能(快进、慢动作、搜索等)。 d(-_-)b