Play a YouTube video in JavaFX?

Moderator action: deleted rant and cleaned up what remains.
I am trying to make this code play an FLV video, and it doesn't show any video. Only Music. How can I convert, for instance, a YouTube video, to play in JavaFX? If I download a YouTube video, how can i encode it?
package musica;
import javafx.application.Application;
import javafx.beans.property.ObjectProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaErrorEvent;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.stage.Stage;
import javafx.util.Duration;
import javax.swing.Action;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
//import javafx.io.http;
* @author André Lopes
public class Musica extends Application {
    public MediaPlayer MP;
    public Media Media;
    public static String URL;
    public static JFileChooser JFC;
    public static Duration currentTime;
    public MediaView mediaView;
    //Main
    public static void main(String[] args) {
        launch(args);
    public Musica()
     currentTime = Duration.ZERO;
     mediaView= new MediaView(MP);
       URL = "";
     //URL = "http://download.oracle.com/otndocs/products/javafx/oow2010-2.flv";
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Hello! This is Yours Music Player!");
        //Botão Play
        Button Play = new Button();
        Play.setText("Play");
        Play.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event1) {
                Media = new Media(URL);
                MP = new MediaPlayer(Media);
                MP.setStartTime(currentTime);
                mediaView.setMediaPlayer(MP);
                MP.play();
                System.out.println("?"+ MP.getStatus());
                mediaView.setOnError(new EventHandler<MediaErrorEvent>() {
                @Override
                public void handle(MediaErrorEvent arg0) {
                            System.out.println("MP.getStatus: " + MP.getStatus());
        //Botão Hello World
        //Botão pra escolher Musica
        Button SelctFileButton = new Button();
        SelctFileButton.setText("Music Chooser/Finder:");
        SelctFileButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
              public void handle(ActionEvent arg0) {
                System.out.println("Java File Chooser Opened");
                JFileChooser search = new JFileChooser();
                search.showDialog(search,URL);
                URL = search.getSelectedFile().toURI().toString();
                System.out.println("URL:"+URL);
       //Botão para pausar;
       Button Pause = new Button();
       Pause.setText("Pause");
       Pause.setFont(Font.font(null, FontPosture.ITALIC,15));
       Pause.setOnAction(new EventHandler<ActionEvent>() {
       @Override
            public void handle(ActionEvent arg0) {
            try {
                currentTime = MP.getCurrentTime();
                MP.pause();  
                }catch(java.lang.NullPointerException e)
                 System.out.println("java.lang.NullPointerException \n");  
                 System.out.println("Error: Unable To pause! May happens if you didnt have a music Playing!");  
       //Botão Para Continuar;
       Button Continue = new Button();
       Continue.setText("Continue/UnPause");
       Continue.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent arg0) {
               //MP.setStartTime(currentTime);
               MP.pause();
        //Grid ! Layout
        GridPane grid = new GridPane();
        StackPane root = new StackPane();
        grid.setHgap(2);
        grid.setHgap(2);
        grid.setVgap(2);
        Scene Scene = new Scene(root,500,500);
        root.getChildren().add(grid);
        root.getChildren().add(mediaView);
        //Scene.getStylesheets().add(Musica.class.getResource("Musica.css").toExternalForm());
        //grid.getStyleClass().add(Musica.class.getResource("Musica.css").toExternalForm());
        primaryStage.setScene(Scene);
        primaryStage.show();
        //Adicionando Botoes no Grid
        grid.add(Play,10,10);
        grid.add(SelctFileButton,11,10);
        grid.add(Pause,10,11);
}Edited by: 932269 on 06/05/2012 20:36
Edited by: 932269 on 06/05/2012 20:37
Edited by: EJP on 8/05/2012 12:02

After the question title has been cleaned up, I can see now that it relates to youtube video playback.
Just embed the youtube html5 video player in a webview and stream video from youtube.
This will work for videos that youtube has made compatible with their html5 player (about 30% it seems).
Here is a sample embedding a youtube hosted trailer uploaded by sony pictures.
import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class YouTubePlayer extends Application {
  public static void main(String[] args) throws Exception { launch(args); }
  @Override public void start(final Stage stage) throws Exception {
    final WebView webView = new WebView();
    webView.getEngine().loadContent(
      "<iframe width=\"640\" height=\"390\" src=\"http://www.youtube.com/embed/IyaFEBI_L24\" frameborder=\"0\" allowfullscreen></iframe>"
    stage.setScene(new Scene(webView, 660, 410));
    stage.show();
}If you have any questions, you can read more about youtube embedding here: https://developers.google.com/youtube/player_parameters

Similar Messages

  • Play a YouTube video using JavaFX components

    I know that we can play a video ( http://zzz/xx/123.flv ), by using the Media View component in JavaFX. In the similar way, is it possible to play a YouTube video in JavaFX ?
    Thank you, for any help in advance.
    Edited by: prabhakar9885 on Sep 17, 2010 4:00 PM

    You might want to take a look at [this thread|http://forums.sun.com/thread.jspa?threadID=5446865], but barring the theoretically possible "hacks" mentioned there, not really.

  • When i try to play a youtube video it plays for only two seconds

    when i try to play a youtube video it plays for only two seconds with sound but the screen stays black. it takes a little more time for the video to load also. then it crashes which ever internet program i am using. But whenever i turn off my plug-ins it works totally fine. how do i fix this? this has never happened to me before. i tried to uninstall flash player and reinstall but it fixes nothing, this has been going on for two days now.
    i use safari and firefox and both dont work

    Click here and download Flash.
    (102455)

  • Firefox 3.6.3 wont play embedded youtube videos. It comes up with "an error occured please try again later. this happens all the time

    Firefox 3.6.3 wont play embedded youtube videos. It comes up with "an error occurred please try again later. this happens all the time. If you click to go to youtube the clip plays.
    == This happened ==
    Every time Firefox opened

    I was having the same issue up until I found a solution myself a few minutes ago. If you have "Accept Third Party Cookies" un-checked it will not allow the embedded "Third party" youtube videos to load. You can either Check the box to allow third party cookies or add an exception to allow youtube.com WITHOUT the www. You just want it to be Youtube.Com.
    To do so just go to Tools: Options: Privacy: Exceptions: Type in Youtube.com and click Allow. Then click Close and OK. It should start working immediately.

  • My macbook pro won't play any youtube video. I always get a plug-in failure message! How can I solve it? I already did all updates, reinstalled flash player but nothing helps!

    My macbook pro won't play any youtube video. I always get a plug-in failure message! How can I solve it? I already did all updates, reinstalled flash player but nothing helps!

    1. System Preferences > Other/ Flash Player > Advanced >  Delete  All
         Press the "Delete All" button
         Install Adobe Flash Player.
        http://get.adobe.com/flashplayer/
        Follow the prompts.
        Quit Safari.
        Restart computer. Relaunch Safari.
    2.  Allow  Plug-ins
        Safari > Preferences > Security
        Internet Plug-ins >  "Allow  plug-ins"
        Enable it.
        Press " Manage Website Settings" button for more options.

  • Safari stop playing embedded youtube videos

    Hi
    I am having trouble with Safari 4.0.5 (6531.22.7) which suddenly refuse to play embedded youtube videos. Safari show the video in a web page but when played the youtube default play display "an error occurred, please try again." and Safari display in the status bar "one error in opening the page, for more information, choose Window->Activity". Now when I look in the activity window it show "forbidden" beside the video file.
    Strangely I can play the same video from the youtube main page without any errors.
    I have already done the following:
    - checked permissions with Disk Utility.
    - Reset Safari
    - Empty caches
    - Removed com.apple.Safari.plist
    - Uninstalled, re-Installed Flash plug-in
    but the problem still persist. Help in resolving will be highly appreciated.

    HI and Welcome to Apple Discussions...
    YouTube streams content using the Flash plugin ... Flash Player support on 64-bit operating systems
    Since you are running Snow Leopard, *try running Safari is opening in 32-bit mode, not 64*. Right or control click the Safari icon in the Applications folder, then click: Get Info In the Get Info window click the black disclosure triangle next to General so it faces down. Select 32 bit mode. Also, (in that same window) *make sure Safari is NOT running in Rosetta.*
    

Web pages now include a small icon or 'favicon' which is visible in the address bar and next to bookmarks. These icons take up disk space and slow Safari down. It is possible to erase the icons from your computer and start fresh. *To delete Safari's icon cache using the Finder, open your user folder, navigate to ~/Library/Safari/ and move this file "webpageIcons.db to the Trash.*
    bpageIcons.db to the Trash.*
    Carolyn

  • Why won't apple tv play some youtube videos it used to play?

    Why won't apple tv play some youtube videos it used to play?

    Ah I see what you mean. Do these specs help:
    Format : MPEG-4
    Format profile : Base Media / Version 2
    Codec ID : mp42
    File size : 525 MiB
    Duration : 20mn 59s
    Overall bit rate : 3 494 Kbps
    Encoded date : UTC 2009-08-19 08:38:05
    Tagged date : UTC 2009-08-19 08:38:35
    Video
    ID : 1
    Format : AVC
    Format/Info : Advanced Video Codec
    Format profile : [email protected]
    Format settings, CABAC : Yes
    Format settings, ReFrames : 5 frames
    Codec ID : avc1
    Codec ID/Info : Advanced Video Coding
    Duration : 20mn 59s
    Bit rate mode : Variable
    Bit rate : 3 333 Kbps
    Width : 1 280 pixels
    Height : 720 pixels
    Display aspect ratio : 16/9
    Frame rate mode : Variable
    Frame rate : 23.976 fps
    Minimum frame rate : 23.810 fps
    Maximum frame rate : 24.390 fps
    Resolution : 24 bits
    Colorimetry : 4:2:0
    Scan type : Progressive
    Bits/(Pixel*Frame) : 0.151
    Stream size : 501 MiB (95%)
    Writing library : x264 core 66 r1114 a933a3e
    Encoding settings : cabac=1 / ref=5 / deblock=1:-1:-1 / analyse=0x3:0x113 / me=umh / subme=7 / psy_rd=1.0:0.0 / mixed_ref=0 / me_range=16 / chroma_me=1 / trellis=1 / 8x8dct=1 / cqm=0 / deadzone=21,11 / chromaqpoffset=-2 / threads=6 / nr=0 / decimate=1 / mbaff=0 / bframes=3 / b_pyramid=1 / b_adapt=1 / b_bias=0 / direct=3 / wpredb=1 / keyint=250 / keyint_min=25 / scenecut=40(pre) / rc=2pass / bitrate=3333 / ratetol=1.0 / qcomp=0.60 / qpmin=10 / qpmax=51 / qpstep=4 / cplxblur=20.0 / qblur=0.5 / ip_ratio=1.40 / pb_ratio=1.30 / aq=1:1.10
    Language : English
    Encoded date : UTC 2009-08-19 08:38:03
    Tagged date : UTC 2009-08-19 08:38:35
    Audio
    ID : 2
    Format : AAC
    Format/Info : Advanced Audio Codec
    Format version : Version 4
    Format profile : LC
    Format settings, SBR : No
    Codec ID : 40
    Duration : 20mn 59s
    Bit rate mode : Constant
    Bit rate : 156 Kbps
    Nominal bit rate : 160 Kbps
    Channel(s) : 2 channels
    Channel positions : L R
    Sampling rate : 48.0 KHz
    Resolution : 16 bits
    Stream size : 23.4 MiB (4%)

  • Only safari adress bar visible after playing a youtube video.

    Only safari adress bar visible after playing a youtube video, rest of the screen is white, what can I do?

    If you are using Safari for Mac, it could be a Safari extension causing this.
    From the Safari menu bar click Safari / Preferences then select the Extensions tab.
    If you have any installed, turn that off, quit then relaunch Safari, try a video.
    It would really help when you post to tell us which operating system you are using, Mac or  Windows.
    You could also try troubleshooting the Flash plugin which is required for most of the content on YouTube.
    http://kb2.adobe.com/cps/865/cpsid_86551.html#ostype=m,prob1=fnctn,prob2=game,

  • Flash causes pc to freeze when playing 2 youtube videos or flash videos at the same time

    I dont know what has caused this issue but since around january my pc has been freezing to the point where i have to hard reset if i play 2 youtube videos or any flash videos at the same time. the whole pc becomes unresponsive when this happens. all my drivers are up to date so i dont know where this issue is coming from.
    My specs:
    Browser- Firefox 28.0
    OS: Windows 7 home edition 64 bit
    Case: Raidmax Platinum
    Motherboard:ASUS M5A99X EVO AM3
    CPU: AMD fx 8350 (4.6ghz oc)
    Cpu Cooler: ZALMAN CNPS10X Performa 120mm
    GPU: msi GTX 670 power edition
    power Supply: Kingwin Kx 1000w
    RAM:2x4gb(8gb) CORSAIR Vengeance240-Pin DDR3 SDRAM
    HDD: Western Digital Caviar Blue 500gb and 640gb
    Bluray: LG Bluray Drive & Burner

    There's two ways you can go about this Amanda.
    1. Set the length of your images for example 8 seconds each. Offset the photo's like a ladder effect and add the animating keyframes. The red dots in the image below represent the start/finish points of the animation.
    2. The other option is to set the length of all the same, then use keyframes to set the start/ finish of the animation.
    I always use example 1, however example 2 would probably be easier to understand?
    Hope that helps
    Tony

  • Error message when trying to play the Youtube video only on Firefox. Is it about regulations or matter of Youtube?

    Ever since Youtube "change casting" (about 6 weeks ago), i can't see anymore a Youtube video even amid other sites or bloggs, with browzer mozilla firefox only (the others do it!!) because all the time sent me an error message when trying to play it. I have downloaded every latest versions of Java, Flash player, Sokwave flash player and i uninstall and reinstall all of them plus the plug ins of Firefox and the Firefox (at the end) when i put the last version 9.1 .I have this problem from updating the v8.0 when mozilla team turn off my java plug in as old (and so many others) but there isn't any new version and i can't uninstall it!.
    Please give me a comprehensive answer to every possible direction. Thank you!

    option-click the video track you want to adjust and drag away or trim away. The audio tracks will remian in place

  • Flash Player Crashes In Internet Explorer 8&9 While Playing HD YouTube Video

    Has anyone else came across this issue? While on YouTube if you try to play a video in HD, it'll play for a second and then crash. This only happens in Internet Explorer. Any suggestions would be helpful. I have tried many things and this is driving me crazy! Thanks in advence for the input.

    So after 4 grueling hours of troubleshooting and trying different fixes, we finally solved the issue. Turns out that we were testing an HD YouTube video just to make sure that Flash Player was functioning without any speakers or headphones plugged in. For some reason when there is no audio device plugged in, the YouTube video starts to play regularly and the reverts to HD. As soon as it changes to HD, it'll crash. Simple as that. So, lesson learned and some advice. Always plug in an audio device. At first when I figured this out, I felt stupid. I then realized that it shouldn't matter if speakers are plugged in or not. A YouTube video should play no matter what if Flash is installed. Anyway, this issue was resolved. Thanks for the input everyone.

  • When I play a youtube video in one tab, then scroll up and down in any tab, the audio from the youtube video gets choppy and cuts out for a second. How to fix?

    I just want to be able to go on other websites and scroll while playing music (smoothly) on youtube in another tab.
    I don't think this happened until after I updated my firefox to 13 and my shockwave flash plug-in to 11.3.300.257
    How can I fix this cutting out and choppy-ness in youtube videos when I scroll?
    Thanks so much!

    Try to disable hardware acceleration.
    *Tools > Options > Advanced > General > Browsing: "Use hardware acceleration when available"
    *https://support.mozilla.org/kb/how-do-i-upgrade-my-graphics-drivers
    Try to "disable the hardware acceleration" in the Flash Player.
    *http://helpx.adobe.com/flash-player/kb/video-playback-issues.html
    See also:
    * https://support.mozilla.org/kb/Cannot+view+full+screen+Flash+videos
    Flash "Display settings" window:
    * http://www.macromedia.com/support/documentation/en/flashplayer/help/help01.html

  • I am not able to play any youtube video on Firefox, while the same video plays on IE and Chrome.

    FireFox was playing youtube videos with no issues until yesterday. Suddenly none of the youtube videos are paying on FireFox. The error message is "An error has occurred. Please try again later"
    I tried the following
    1. Uninstall and Reinstall Firefox
    2. Uninstall and Reinstall Flash
    3. Restart my laptop
    No luck with anything. The same videos play fine on IE and Chrome.

    Hi mje397,
    Sorry for the delay. I have been investigating this and it may have to do with saved preferences on the computer. If you right click and select "Global Settings" remove stored preferences. I could not find any outage notifications for Youtube.
    Also disable Flash and try the HTML5 player just in case this is a plug in issue. This can happen specifically when there are network issues or there are changes being made to the videos on the hosted site.
    Please post back with your results, it could help other users!

  • I am not able to play any youtube video it is showing error.

    I am able to play youtube videos on chrome but not in the latest version of firefox i.e 32.0.1

    Check Your Connection. Update your Flashplayer. Hope this helps..

  • Flash player wont play my youtube videos after i updated it on mozilla firefox to latest version

    I updated my flash player to the latest version 11.6.602.180 after not updating it for a very longtime. Now my youtube wont play videos just shows black screen. If i disable
    the plugin the videos play but there is a message which says plug in disabled/manage plug ins. What should i do???? If i use internet explorer the videos play on youtube but i also want them to play for firefox just like before.pliz help i do not know the previous plug in i had?

    I am having the same issue in Chrome... so checked Youtube in Firefox and IE... It's a Youtube issue!  Videos load a few seconds at a time and makes the playback horrible... unusable!  Wish someone at Google or Adobe would fix it!

Maybe you are looking for

  • Help plotting points in a java Applet using Bresens Algorithm

    Hi, I am trying to compile my code and it doesn't like POINT. I am guesing I am using the wrong thing. Point.point(Math.round(x), Math.round(y)); and I tried just Point. How do I plot points so that it forms a line. What internal function do I use? H

  • Dynamic filter in Design studio using drop-down when data source is Universe

    Hi community, Is there anyway to create Cascading filter in Design studio when data source is Universe using drop-down component (Dimension filters cannot be used in my requirement). My requirement is, I have 2 drop-downs: drop-down 1 : shows the reg

  • Execution in new thread

    I have a Sequence File composed of a Mainsequence & Subsequence. Inside of the MainSequence, I called a Subsequence in a new thread. Now, I want to run Subsequence until the Mainsequence triggers stopping of this Subsequence. Any suggestion on how to

  • Soundbooth CS4 crashing on startup...

    I've looked elsewhere on the forum, but it doesn't appear this has been answered. I'm getting the following error when on startup of Adobe Soundbooth CS4: "/Gogo/main/MediaCore/ASL/Foundation/Make/Mac/../../Src/DirectoryRegi stry.cpp-283". In fact, i

  • PEAP with Novell NDS and LDAP?

    I was reading this Cisco Q&A doc (http://www.cisco.com/en/US/products/hw/wireless/ps430/products_qanda_item0900aecd801764fa.shtml) that contained the following question and answer: Q. Can I use PEAP with LDAP or Novell NDS databases? A. Yes. PEAP pro