現在、Java FX でこれを実現する最善の方法は、組み込み HTTP サーバーを使用し、HTTP ライブ ストリーミング (ビデオ オン デマンド) を使用することです。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 形式であると想定していることに注意してください。やるべきことは、それを .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