Как сделать просмотр медиа со ссылкой с YouTube в Java fx - PullRequest
0 голосов
/ 26 мая 2020

Я хочу использовать представление мультимедиа в Scene Builder, чтобы при нажатии кнопки воспроизводилось видео из ссылки YouTube, которую я дал ему раньше. Как мне go это сделать?

Я не хочу, чтобы браузер открывался при нажатии, я хочу, чтобы это видео воспроизводилось в поле просмотра мультимедиа.

1 Ответ

0 голосов
/ 27 мая 2020

Вот довольно простой пример, чтобы вы начали использовать Web View Control. Он берет URL-адрес YouTube и преобразует его во встроенный.
Изображение для предварительного просмотра

Я предоставил два примера: один как полный отдельный класс, а другой - с использованием построителя сцены.

Пример 1: Полный одиночный класс

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

Пример 2: Использование Scene Builder

F XML файл (sample.f xml):

<?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. 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. 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);
    }
}
...