Play a Youtube video using JavaFX
Asked Answered
R

3

14

I'm trying to play a video from youtube using javaFX. Here is my code

public class Main extends Application {

public static void main(String[] args) {
    launch(args);
}

@Override
public void start(Stage primaryStage) throws Exception {
    primaryStage.setTitle("Media");
    Group root = new Group();
    Media media = new Media("http://www.youtube.com/watch?v=k0BWlvnBmIE");
    MediaPlayer mediaPlayer = new MediaPlayer(media);
    mediaPlayer.play();

    MediaView mediaView = new MediaView(mediaPlayer);

    root.getChildren().add(mediaView);
    Scene scene = SceneBuilder.create().width(500).height(500).root(root)
            .fill(Color.WHITE).build();
    primaryStage.setScene(scene);
    primaryStage.show();
}

}

The window opens but video doesn't play and there is no exception. What is the problem and how can i fix it.

Thanks.

Rafaelof answered 12/9, 2013 at 7:27 Comment(1)
check this link :reddit.com/r/java/comments/6jb4ep/…Marris
D
22

Update Oct 2021

I tried this solution again using JavaFX 17, it worked fine for me, which is kind of nice six years later.

Note that the video in the original example is no longer hosted on YouTube, but you would want to play a different video anyway.

To do so, just substitute the video id part of the url utUPth77L_o with the id of your video (which you can see in the url when you play it in YouTube).

Example URLs which worked in 2021:

The watch linked videos display the full YouTube site, the embed linked videos just display the YouTube player for the video.

YouTube does force some videos to be displayed on its site rather than using the embed link, so even if the video can be watched on YouTube via the watch URL, the embed link won't always work, but the watch link should work OK in WebView for such cases.

Update Dec 4th 2015

Some versions of JavaFX 8 are unable to play back youtube video content. Currently, for instance, Java 8u66 cannot playback youtube video content, but Java 8u72 early access release can.

Background

General information on playing video in JavaFX is located in my answer to: Any simple (and up to date) Java frameworks for embedding movies. This answer just deals with embedding YouTube videos as that appears to be what the question asker is interested in.

Solution

JavaFX can play a YouTube video using a YouTube video URL if you supply the URL to a WebView rather than a MediaPlayer.

Considerations

If you just want the YouTube media player and not the whole related YouTube page, use the /embed location rather than the /watch location in the URL.

Only some videos can be embedded. For instance, you can't embed the Katy Perry video because YouTube blocks it's distribution in an embedded format (instead telling you to view the video on the YouTube site, where it is only provided through the YouTube Flash player).

Only videos which YouTube allow to play in their HTML5 player may be played in JavaFX. This is a pretty large percentage of YouTube videos. YouTube videos which only play in YouTube's Flash player do not play in JavaFX.

Sample Application

The JavaFX application below plays a YouTube video advertisement for a piece of fruit.

fruit

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class VideoPlayer extends Application {    
  public static void main(String[] args) { launch(args); }

  @Override public void start(Stage stage) throws Exception {
    WebView webview = new WebView();
    webview.getEngine().load(
      "http://www.youtube.com/embed/utUPth77L_o?autoplay=1"
    );
    webview.setPrefSize(640, 390);

    stage.setScene(new Scene(webview));
    stage.show();
  }    
}
Drab answered 12/9, 2013 at 10:7 Comment(4)
Hi Jewelsea, I am using same code in our application but this code is not able to play youtube video. Application view is successfully open but after giving error message when its try to play. we are facing some this kind of error in the view section Error:- "An error occurred. Please try again later". So please let me what is the exact problem.Bingen
I just tried running the code from my answer again on Java 8u40 on OS X 10.9.5 and the video played perfectly fine.Drab
would there be any way to cast the Webview node into a MediaYod
@Hilea No, I don't think you can cast the WebView node into a Media node.Drab
S
3

JavaFX can't play youtube video just with the video url. you need to specify the file of your video, not just a random youtube link. Try with this URL : http://download.oracle.com/otndocs/products/javafx/oow2010-2.flv your code works fine

Surinam answered 12/9, 2013 at 8:29 Comment(1)
Note: Recent JavaFX versions no longer support flv playback (mp4 files should play back fine). Playing videos via YouTube watch and embed URLs loaded into WebView (as demonstrated in my answer) also works, in addition to URLs directly pointing to video files as demonstrated in this answer.Drab
M
0

I've tried the solution that was recommended, but it didn't work for me (JavaFX: 17.0.6, Java 17). Instead, I used yt-dlp to get the stream_url (url), and the video streamed perfectly.

To do this, you can run the command:

yt-dlp --dump-json <YouTube video link>

to get the JSON metadata for the YouTube video. Then, you can parse the JSON using any JSON library to extract the url key. Once you have the url, you can use it to play the video using Media, MediaPlayer, and MediaView.

I am using JProc to spawn a yt-dlp instance and the json-simple library to parse the JSON.

var process = new ProcBuilder(ytDlpPath, "--dump-json", "https://www.youtube.com/watch?v=t5b20oLaIaw")
            .withNoTimeout();

var output = process.run().getOutputString();

var jsonOutput = (JSONObject) new JSONParser().parse(output);
var streamUrl = jsonOuput.get("url");

var root = new Group();

var media = new Media(streamUrl);
var mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();

var mediaView = new MediaView(mediaPlayer);

root.getChildren().add(mediaView);

Scene scene = new Scene(root, 800, 600);
stage.setTitle("Hello!");
stage.setScene(scene);
stage.show();
Mandragora answered 18/7 at 17:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.