如何更改媒体播放器中的媒体而不是vlcj中的mediaplayercomponent?

时间:2018-02-05 10:51:03

标签: swing javafx vlcj

我正在使用 swing vlcj 制作桌面应用程序。我把框架分成了两个部分的一面webbrowser,它有几个视频的url,另一个面板vlcj在mediaplayer中播放那个url。您选择的第一个网址工作正常并显示在播放器中。问题是,在我选择另一个网址之后,我想要将第一个网址替换为第二个网址。处理第一个媒体然后播放第二个媒体的正确方法是什么?第二个问题是我在面板中设置了vlcj但是它在vlc直接3d输出中打开视频你能告诉我它为什么不在面板画布中打开。 这是我尝试的代码:

import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSlider;
import javax.swing.JSplitPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.event.ChangeEvent;
import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.binding.LibVlcConst;
import uk.co.caprica.vlcj.discovery.NativeDiscovery;
import uk.co.caprica.vlcj.player.MediaPlayer;
import uk.co.caprica.vlcj.player.MediaPlayerEventAdapter;
import uk.co.caprica.vlcj.player.MediaPlayerFactory;
import uk.co.caprica.vlcj.player.embedded.EmbeddedMediaPlayer;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;
/**
 *
 * @author biznis
 */
public class NewJFrame extends javax.swing.JFrame {
JScrollPane scrollableTextArea;
    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        initComponents();
            //JFrame jFrame2 = new JFrame("vlcj Tutorial");
        MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory();
        canvas1.setBackground(Color.black);
       jPanel2.setLayout(new BorderLayout());
     jPanel2.setPreferredSize(new Dimension(200,300));
         jPanel2.add(canvas1, BorderLayout.CENTER);

        // frame.add(jPanel2, BorderLayout.NORTH);
      //  frame.add(p, BorderLayout.CENTER);
         EmbeddedMediaPlayer mediaPlayer = mediaPlayerFactory.newEmbeddedMediaPlayer();
        mediaPlayer.setVideoSurface(mediaPlayerFactory.newVideoSurface(canvas1));

         //jPanel2.setLayout(new java.awt.CardLayout());
          //jFrame2.setVisible(true);
        //jFrame2.setLocation(100, 100);

       JPanel p1 = new JPanel();

        p1.setBounds(100, 900, 105, 200);
      jPanel2.add(p1, BorderLayout.SOUTH);
         JButton playbutton = new JButton();

        playbutton.setIcon(new ImageIcon("C:/Users/biznis/Desktop/Newspaper/sangbadpratidin/d/play.png"));
        //  this.setSize(800,450);
        playbutton.setBounds(50, 50, 150, 100);
        playbutton.setToolTipText("Play");
        p1.add(playbutton);

        JButton pausebutton = new JButton();

        pausebutton.setIcon(new ImageIcon("C:/Users/biznis/Desktop/Newspaper/sangbadpratidin/d/pause.png"));
        pausebutton.setToolTipText("pause");
        pausebutton.setBounds(80, 50, 150, 100);

        p1.add(pausebutton);
        JButton previousbutton = new JButton();
        previousbutton.setIcon(new ImageIcon("C:/Users/biznis/Desktop/Newspaper/sangbadpratidin/d/previous.png"));
        previousbutton.setBounds(90, 50, 150, 100);
        previousbutton.setToolTipText("Skip back");
        p1.add(previousbutton);
        JButton nextbutton = new JButton();
        nextbutton.setIcon(new ImageIcon("C:/Users/biznis/Desktop/Newspaper/sangbadpratidin/d/next.png"));
        nextbutton.setBounds(90, 50, 150, 100);
        nextbutton.setToolTipText(" Skip forward");
        p1.add(nextbutton);
        JButton captureButton = new JButton();

        captureButton.setIcon(new ImageIcon("C:/Users/biznis/Desktop/Newspaper/sangbadpratidin/d/icons8-unsplash-26.png"));
        captureButton.setToolTipText("capture");
        captureButton.setBounds(80, 50, 150, 100);

        p1.add(captureButton);
        JSlider volumeSlider = new JSlider();
        volumeSlider.setMinimum(LibVlcConst.MIN_VOLUME);
        volumeSlider.setMaximum(LibVlcConst.MAX_VOLUME);
        volumeSlider.setPreferredSize(new Dimension(100, 40));
        volumeSlider.setToolTipText("Change volume");
        p1.add(volumeSlider);
        JSlider js = new JSlider();
      p1.add(js);
         // mediaPlayer.playMedia("D:\\test\\192.168.2.201_01_20180124_153000.avi");
         js.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent e) {
                if (js.getValue() / 100 < 1) {
                    mediaPlayer.setPosition((float) js.getValue() / 100);
                }
            }
        });

        Timer timer = new Timer(100, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                js.setValue(Math.round(mediaPlayer.getPosition() * 100));
            }

        });

        timer.start();
        pausebutton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                mediaPlayer.pause();
                // or mediaPlayer.pause() depending on what works.
                final long time = mediaPlayer.getTime();
                System.out.println(time);

            }
        });
        playbutton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                mediaPlayer.play();
            }
        });
        previousbutton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {

                mediaPlayer.skip(-10000);
            }
        });
        nextbutton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                mediaPlayer.skip(1000);
            }
        });
        volumeSlider.addChangeListener(new javax.swing.event.ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                mediaPlayer.setVolume(volumeSlider.getValue());
            }
        });
        captureButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                File file3 = new File("C:/Test/");
                mediaPlayer.saveSnapshot(file3);
                try {
                    BufferedImage image3 = ImageIO.read(file3);
                } catch (IOException ex) {
                    Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });





         JFXPanel jfxPanel = new JFXPanel();
jPanel1.add(jfxPanel);

// Creation of scene and future interactions with JFXPanel
// should take place on the JavaFX Application Thread
Platform.runLater(() -> {
    WebView webView = new WebView();
   WebEngine wb1 = webView.getEngine();
    jfxPanel.setScene(new Scene(webView));
    wb1.load("");
    wb1.getLoadWorker().stateProperty()
                .addListener(new ChangeListener<Worker.State>() {
                    @Override
                    public void changed(ObservableValue ov, Worker.State oldState, Worker.State newState) {
                        if (newState == Worker.State.SCHEDULED) {
                          frame.setTitle(wb1.getLocation());
                            String trgurl = wb1.getLocation();
                            System.out.println(trgurl);
                              if (trgurl.matches("(.*)video=(.*)")) {


                                  int n = trgurl.indexOf("video=");
                                  //String str1 = Integer.toString(n);
                                  System.out.println(n + 6);
                                  int len = trgurl.length();
                                  System.out.println("string length is: " + trgurl.length());
                                  System.out.println(trgurl.substring(n+6,len));
                                  String find =  "file:" +trgurl.substring(n+6,len);
                                  System.out.println(find);
                                 //   mediaPlayer.setVideoSurface(mediaPlayerFactory.newVideoSurface(canvas1));

                              mediaPlayer.prepareMedia(find);
                              mediaPlayer.start();

                        JScrollPane scrollableTextArea = new JScrollPane(jPanel2);  

        scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);  
        scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);  




        }
    }
                }
});
        });
    } 

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
         jPanel1.setPreferredSize(new Dimension(200, 300));
        canvas1 = new java.awt.Canvas();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(500, 300));
        getContentPane().setLayout(new java.awt.GridLayout());
        getContentPane().add(jPanel2);

        jPanel1.add(canvas1);

        getContentPane().add(jPanel1);
      // getContentPane().add(sp);

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(final String[] args) {
        /* Set the Nimbus look and feel */
        new NativeDiscovery().discover();
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
         SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {

                 frame = new NewJFrame();

                frame.setVisible(true);

            }
        });
    }
private static NewJFrame frame;
    // Variables declaration - do not modify                     
    private java.awt.Canvas canvas1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    // End of variables declaration                   
  }

在jpanel1 im openning vlcj和jpanel2 webview中。请帮忙。提前谢谢。

当我点击视频的下一个链接时,这是异常日志:

Exception in thread "JavaFX Application Thread" java.lang.IllegalStateException: The video surface component must be displayable
    at uk.co.caprica.vlcj.player.embedded.videosurface.CanvasVideoSurface.attach(CanvasVideoSurface.java:75)
    at uk.co.caprica.vlcj.player.embedded.DefaultEmbeddedMediaPlayer.attachVideoSurface(DefaultEmbeddedMediaPlayer.java:156)
    at uk.co.caprica.vlcj.player.embedded.DefaultEmbeddedMediaPlayer.onBeforePlay(DefaultEmbeddedMediaPlayer.java:315)
    at uk.co.caprica.vlcj.player.DefaultMediaPlayer.play(DefaultMediaPlayer.java:705)
    at uk.co.caprica.vlcj.player.DefaultMediaPlayer.playMedia(DefaultMediaPlayer.java:222)
    at javaapplication6.NewJFrame$9.changed(NewJFrame.java:231)
    at javaapplication6.NewJFrame$9.changed(NewJFrame.java:211)
    at com.sun.javafx.binding.ExpressionHelper$SingleChange.fireValueChangedEvent(ExpressionHelper.java:182)
    at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
    at javafx.beans.property.ReadOnlyObjectPropertyBase.fireValueChangedEvent(ReadOnlyObjectPropertyBase.java:74)
    at javafx.beans.property.ReadOnlyObjectWrapper.fireValueChangedEvent(ReadOnlyObjectWrapper.java:102)
    at javafx.beans.property.ObjectPropertyBase.markInvalid(ObjectPropertyBase.java:112)
    at javafx.beans.property.ObjectPropertyBase.set(ObjectPropertyBase.java:146)
    at javafx.scene.web.WebEngine$LoadWorker.updateState(WebEngine.java:1287)
    at javafx.scene.web.WebEngine$LoadWorker.dispatchLoadEvent(WebEngine.java:1388)
    at javafx.scene.web.WebEngine$LoadWorker.access$1200(WebEngine.java:1280)
    at javafx.scene.web.WebEngine$PageLoadListener.dispatchLoadEvent(WebEngine.java:1267)
    at com.sun.webkit.WebPage.fireLoadEvent(WebPage.java:2499)
    at com.sun.webkit.WebPage.fwkFireLoadEvent(WebPage.java:2343)
    at com.sun.webkit.WebPage.twkProcessMouseEvent(Native Method)
    at com.sun.webkit.WebPage.dispatchMouseEvent(WebPage.java:807)
    at javafx.scene.web.WebView.processMouseEvent(WebView.java:1045)
    at javafx.scene.web.WebView.lambda$registerEventHandlers$32(WebView.java:1168)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.EmbeddedScene.lambda$null$293(EmbeddedScene.java:256)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.EmbeddedScene.lambda$mouseEvent$294(EmbeddedScene.java:244)
    at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
    at java.lang.Thread.run(Thread.java:748)

1 个答案:

答案 0 :(得分:0)

Thnx我通过左右面板和滚动窗格解决了这个问题。

import java.awt.*;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javax.swing.*;
import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.discovery.NativeDiscovery;



public class MyTestClass extends JFrame {
EmbeddedMediaPlayerComponent playerCmpt;
    public MyTestClass() {
        new NativeDiscovery().discover();

        EmbeddedMediaPlayerComponent playerCmpt = new EmbeddedMediaPlayerComponent();
       playerCmpt.setPreferredSize(new Dimension(200, 100));

        JPanel leftPane = new JPanel();
        leftPane.setPreferredSize(new Dimension(100, 100));
        JFXPanel jfxPanel = new JFXPanel();
leftPane.add(jfxPanel);
//jPanel1.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
//jPanel1.setBorder(new EmptyBorder(20, 20, 20, 20));
// Creation of scene and future interactions with JFXPanel
// should take place on the JavaFX Application Thread
Platform.runLater(() -> {
    WebView webView = new WebView();
   WebEngine wb1 = webView.getEngine();
    jfxPanel.setScene(new Scene(webView));
    wb1.load("");
    wb1.getLoadWorker().stateProperty()
                .addListener(new ChangeListener<Worker.State>() {
                    @Override
                    public void changed(ObservableValue ov, Worker.State oldState, Worker.State newState) {
                        if (newState == Worker.State.SCHEDULED) {
                      //    this.setTitle(wb1.getLocation());
                            String trgurl = wb1.getLocation();
                            System.out.println(trgurl);
                              if (trgurl.matches("(.*)video=(.*)")) {


                                  int n = trgurl.indexOf("video=");
                                  //String str1 = Integer.toString(n);
                                  System.out.println(n + 6);
                                  int len = trgurl.length();
                                  System.out.println("string length is: " + trgurl.length());
                                  System.out.println(trgurl.substring(n+6,len));
                                  String find =  "file:" +trgurl.substring(n+6,len);
                                  System.out.println(find);
                                  //   mediaPlayer.setVideoSurface(mediaPlayerFactory.newVideoSurface(canvas1));

                                 // mediaPlayer.release();
                                  playerCmpt.getMediaPlayer().playMedia(find);

                                  // mediaPlayer.stop();
                         // mediaPlayer.prepareMedia(find);

                         // mediaPlayer.stop();
                          //mediaPlayer.prepareMedia(find);
                                  //JScrollPane scrollableTextArea = new JScrollPane(jPanel2);
                                  //scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
                                  //scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);




        }
    }
                }
});
        });


        JPanel playerPanel = new JPanel(new BorderLayout());
        playerPanel.add(playerCmpt);

        JSplitPane mainSplit = new JSplitPane(
            JSplitPane.HORIZONTAL_SPLIT,
            leftPane, playerPanel);

        playerPanel.setMinimumSize(new Dimension(10, 10));

        this.add(mainSplit);
        this.pack();
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //playerCmpt.getMediaPlayer().playMedia("D:\\test\\192.168.2.201_01_20180124_153000.avi");

    }

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