Play a Youtube Video Using Javafx

Play a Youtube video using JavaFX

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:

  • https://www.youtube.com/watch?v=P_tAU3GM9XI
  • https://www.youtube.com/embed/P_tAU3GM9XI?autoplay=1

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();
}
}

Play Youtube Video in JavaFX

This code is not working when I was running this on IDE(Eclipse, NetBeans or IntelliJ). But when I am Exporting this from Eclipse IDE as "Runnable JAR file", and running the Jar file, it's working perfectly. It seems, it's just not running on IDE.

How to make a Media view with a link from YouTube in Java fx

Here is a rather minimal example to get you started making use of Web View Control. It takes a YouTube URL and convert it into an embedded one.

Preview Image

I have provided two examples one as a complete single class and another using the scene builder.

Example 1: Complete Single class

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main extends Application {
public class YTPlayer extends VBox{
private Button plyButton;
private WebView webView4 = new WebView();
private HBox hBox;
private TextArea textArea;
private String url = "";
private final Pattern pattern = Pattern.compile("(?<=watch\\?v=|/videos/|embed\\/|youtu.be\\/|\\/v\\/|\\/e\\/|watch\\?v%3D|watch\\?feature=player_embedded&v=|%2Fvideos%2F|embed%\u200C\u200B2F|youtu.be%2F|%2Fv%2F)[^#\\&\\?\\n]*");
public YTPlayer(double width, double height){
super();
this.setPrefHeight(height);
this.setPrefWidth(width);

hBox = new HBox();
hBox.setPrefHeight(0.045*height);
hBox.setPrefWidth(width);
textArea = new TextArea();
textArea.setPrefHeight(0.175*height);
textArea.setPrefWidth(0.913*width);
textArea.setPromptText("URL");

plyButton = new Button();
plyButton.setPrefHeight(0.095*height);
plyButton.setPrefWidth(0.0867*width);
plyButton.setText("Play");
plyButton.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
if(!textArea.getText().equals("")){
setUrl(textArea.getText());
play();
}
}
});
hBox.getChildren().addAll(plyButton,textArea);
webView4.setPrefHeight(0.9025*height);
webView4.setPrefWidth(width);
this.getChildren().addAll(webView4,hBox);
}
void play (){
webView4.getEngine().load(this.url);
}
void setUrl(String url){
Matcher matcher = pattern.matcher(url);
if(matcher.find()){
this.url ="https://www.youtube.com/embed/"+matcher.group(0);
System.out.println(this.url);
}else{
System.out.println("Invalid Url!");
}
}
}
@Override
public void start(Stage primaryStage) throws Exception{
double sceneWidth = 600;
double sceneHeight =400;
YTPlayer player =new YTPlayer(sceneWidth,sceneHeight);
Pane root = new Pane();
root.getChildren().addAll(player);
Scene myscene =new Scene(root, sceneWidth,sceneHeight);
primaryStage.setScene(myscene);
primaryStage.show();
}

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

Example 2: Using Scene Builder

FXML file (sample.fxml) :

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.web.*?>

<VBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/10.0.2-internal" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
<children>
<WebView fx:id="webView" prefHeight="361.0" prefWidth="600.0" />
<HBox prefHeight="18.0" prefWidth="600.0">
<children>
<Button mnemonicParsing="false" onAction="#play" prefHeight="38.0" prefWidth="52.0" text="Play" />
<TextArea fx:id="urlTxtArea" prefHeight="7.0" prefWidth="548.0" promptText="URL" />
</children>
</HBox>
</children>
</VBox>

Controller class (Controller.java):

import javafx.fxml.FXML;
import javafx.scene.control.TextArea;
import javafx.scene.web.WebView;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Controller {
private final Pattern pattern = Pattern.compile("(?<=watch\\?v=|/videos/|embed\\/|youtu.be\\/|\\/v\\/|\\/e\\/|watch\\?v%3D|watch\\?feature=player_embedded&v=|%2Fvideos%2F|embed%\u200C\u200B2F|youtu.be%2F|%2Fv%2F)[^#\\&\\?\\n]*");
private String url;

@FXML
private WebView webView;

@FXML
private TextArea urlTxtArea;

@FXML
void play() {
if(!urlTxtArea.getText().equals("")){
Matcher matcher = pattern.matcher(this.urlTxtArea.getText());
if(matcher.find()){
this.url ="https://www.youtube.com/embed/"+matcher.group(0);
webView.getEngine().load(this.url);
System.out.println(this.url);
}else{
System.out.println("Invalid Url!");
}
}
}
}

Main class (Main.java):

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Simple Youtube video Player");
primaryStage.setScene(new Scene(root, 600, 400));
primaryStage.show();
}

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


Related Topics



Leave a reply



Submit