Get the URL of a YouTube FLV in Flash

YouTube recently changed the way it serves FLV videos and previous methods to get the URL of the FLV files no longer work. As a workaround, it is still possible to retrieve it by:

1. Downloading the YouTube webpage where the video is embedded
2. Parsing it to extract the “t” and “video_id” parameters
3. Building the FLV URL using the old method.

Obviously, having to download and parse the YouTube web page is a lot slower than the previous method, which was just about reading the HTTP headers, but at least it works.

The code snippet below allows to do just that:

public function getFLVURL(iYouTubeVideoURL) {
  // iYouTubeVideoURL is the "watch" URL such as:
  // http://www.youtube.com/watch?v=OVVvAnU3m6E

  var loader:URLLoader = new URLLoader();
  var req:URLRequest = new URLRequest(iYouTubeVideoURL);
  loader.addEventListener(Event.COMPLETE, this.getFLVURL_complete);
  loader.addEventListener(IOErrorEvent.IO_ERROR, this.getFLVURL_ioError);
  loader.load(req);
}

private function getFLVURL_complete(iEvent) {
  var pageData:String = iEvent.currentTarget.data;

  // Get the "t" parameter
  var regex:RegExp = /"t": "(.*?)"/;
  var result:Array = pageData.match(regex);
  if (result.length < 2) {
    trace("Error parsing YouTube page: Couldn't get 't' parameter");
    return;
  }
  var param_t = result[1];

  // Get the "video_id" parameter
  regex = /"video_id": "(.*?)"/;
  result = pageData.match(regex);
  if (result.length < 2) {
    trace("Error parsing YouTube page: Couldn't get 'video_id' parameter");
    return;
  }
  var param_video_id = result[1];

  var flvURL:String = constructFLVURL(param_video_id, param_t);
  trace("Here's the FLV URL: " + flvURL);

  flvTextBox.text = flvURL;
}

private function getFLVURL_ioError(iEvent) {
  var loader = iEvent.target;
  trace("Couldn't download YouTube web page: " + iEvent);
}

private function constructFLVURL (video_id:String, t:String):String {
  var str:String = "http://www.youtube.com/get_video.php?";
  str += "video_id=" + video_id;
  str += "&t=" + t;
  return str;
}

Update (01/12/2008):

As it turns out, this technique only works from Adobe AIR and not from a web page. This is because YouTube doesn’t allow crossdomain calls, which means that if a Flash application tries to fetch one of their pages, it will fail with a security error.

To go around this issue, it is possible to use a simple PHP stub file, which fetches the YouTube page and send it back to Flash. The PHP file would be as follow:

<?php

$url = urldecode($_GET["url"]);
header("Content-Type: text/html");
readfile($url);

?>

Then, in Flash, instead of calling the YouTube URL directly, you call the PHP URL:

var youTubeURL = "http://uk.youtube.com/watch?v=bxfpMGLMZ7Y"
var stubURL = "http://example.com/stub.php?url=" + escape(youTubeURL)
getFLVURL(stubURL);

This small demo illustrates all that. The source code with PHP stub is available here.

Update (19/03/2009):

I’ve posted a follow up to this post with some information on how to get the HD quality version of the videos:
Get the URL of an HD-quality Youtube video.

Tags: , ,

33 Responses to “Get the URL of a YouTube FLV in Flash”

  1. gui Says:

    unfortunately this method only works when testing inside of flash. if you export an HTML and run it online, it will generate a sandbox violation.
    i’m still looking for a work around on this

  2. admin Says:

    Right, I didn’t notice that as I was only using this technique from Adobe AIR.

    I guess that’s because YouTube is blocking all external calls in their crossdomain.xml file. One way around that is to use a PHP stub file to redirect the YouTube URL. So the PHP file would parse the HTML and send it back to Flash. I’ve made a small demo here that works well: http://pogopixels.com/download/flvurl/

  3. FlexCamp 2008 Belgium | Peter Elst Says:

    […] for download here (including the updated YouTube class to get hold of FLV files, thanks to Pogopixels!) addthis_url = […]

  4. Flex Youtube Interface « My Flexible Experiments Says:

    […] get the rid of the cross-domain issue ,  I followed the instructions on this […]

  5. hermy Says:

    Don’t work. Is there an new solution?

    Thanks.

  6. Laurent Says:

    hermy, what doesn’t work? I just gave it another try and it’s still working for me.

  7. Flexit Says:

    Since yesterday, I can’t get it to work on com domain even with the server code, I get some kind of weird security error only when I try to load the final URL from a browser. Whats funny is that the t param and all others are there, but the final URL is invalid.
    If I try the same code from my test domain all is fine…

  8. Laurent Says:

    Indeed, it looks like they’ve changed the API again, as I’m now getting a “403 forbidden” error when I try to download the FLV file. DownloadHelper is now generatting a URL such as this one:

    http://v21.lscache7.googlevideo.com/videoplayback?id=37969de7d35f0384&itag=34&sparams=id%2Cexpire%2Cip%2Cipbits%2Citag&ip=86.135.120.157&signature=414F72F319A1CEAFC294EE37B2FA353038B47136.09D8154014CD141E5F74C169CD3C1DAE100E8739&sver=3&expire=1238948472&key=yt1&ipbits=0#/Grafite_Vs_Bayern_Tor_des_Jahres_attachment_filename_video.flv

    I’m not sure how to build such URL but I’ll take a look at it when I have time. Thanks for letting me know.

  9. chazen Says:

    Hi ,
    May I ask a question.
    How to use the snippet-as3-code in my flash file. Should I save the code in *.as then use it in fla or just write the code in key-frame ?
    It seems that I have to creat one dynamic text box named flvTextBox to receive the parsing result, am I right ?

    When I pasted the code in fla file and compile it, some snytax wrong !~ How should I modify it ?

    I’am not familiar with how O.O. language using , thanks all very much.

    Chazen
    2009.05.25

  10. Vipin Says:

    Hi,

    I am using Flash for a desktop application, and I wanted to use your script in my app…

    As expected, I am getting a Security Sandbox exception…Where and how should i put and call the STUB.PHP file in this case? Please reply back with the answer…

    Thanking you in anticipation for an answer…

    -Vipin

  11. Laurent Says:

    Do you have a crossdomain.xml file at the root of your domain? It should be formatted like this one:
    http://pogopixels.com/crossdomain.xml

  12. Vipin Says:

    huh…that was easy….
    Thanks Laurent…

  13. Vipin Says:

    Hey Laurent,
    Just one more question…I have got the YouTube URL (the ‘t’ variable and other things) using a flash desktop application (not a web based one). How can I stream (play) this gotten URL in my desktop application? (I can’t put the PHP code because there is no server involved!!! )

    Replies appreciated…

    -Vipin

  14. Flash developer tutorials/links that are neat-o-burrito :} » Djack Height Blog Says:

    […] Link: http://pogopixels.com/blog/getting-the-url-of-a-youtube-flv-file-in-flash/ […]

  15. ayda Says:

    Hii

    I am tring to use your code but I have a problem,it seems that the code does not connect to php file,I just did as you said,is there anything else that I sould do?

    Thanks in advance

  16. Flex Video Gallery-Youtube Template « Vinod_danims Blog Says:

    […] get the rid of the cross-domain issue ,  I followed the instructions on this […]

  17. chris Says:

    Any luck getting this to actually work?

  18. Mahesh Says:

    Hi… im reading this post for quite a long..but dint figured out what to do with that link which your demo application gives..like…i gave an you tube URL as input “http://www.youtube.com/watch?v=uhOUdfYIKEg” and it gave me the another URL like this “http://www.youtube.com/get_video.php?video_id=uhOUdfYIKEg&t=vjVQa1PpcFNa9dIHreuRU3IqYB3p35P6ZYYKU7BqBn8=” So what should i actually do with that latter URL becoz im trying to stream a Youtube video in a flex application..but videoDisplay component in Flex accepts URL with formats like “www.somedomain.com/samplevideofile.flv” ANY HELP

  19. » Flex Video Gallery-Youtube Template CHIPKIDZ- Open Source Youth Employment Centre Says:

    […] get the rid of the cross-domain issue , I followed the instructions on this […]

  20. luciano_dev Says:

    Great!!! Great!!! Great!!! Great!!! Great!!! Great!!! Great!!!
    Work!!!!! Great!!! Great!!! Great!!! Great!!! Great!!! Great!!!
    Clap Clap Clap Clap Clap Clap Clap Clap Clap Clap Clap Clap

    =)

  21. azz kikr Says:

    fail

  22. azz kikr Says:

    like cmon hows anyone supposed to figure out anything with those codes? half of ’em dont work and i still cant find the URL

  23. luciano_dev Says:

    changes in youtube, the script fail

    =(

  24. luciano_dev Says:

    Found found again!!!! come on!!!!!

  25. Swami Charan Says:

    @Mahesh,

    The URL we get will point to the FLV of that video. We need to pass the result to NetStream.play().

    In Flash, if we pass the “http://www.youtube.com/get_video.php?video_id=uhOUdfYIKEg&t=vjVQa1PpcFNa9dIHreuRU3IqYB3p35P6ZYYKU7BqBn8=” to NetStream.play(), it will play the video.

    -Swami

  26. artibaj Says:

    When i get the url of youtube flv (with stub.php file)
    and i add this to NetStream object to play
    i get in Flash error:
    Error opening URL
    ‘http://www.youtube.com/get_video.php?video_id=Th3gmJ_MFNo&t=vjVQa1PpcFMBLVhBx6rxYxgGP1Ka43csLJdXEJB5cjg

    when i get url of flv without stub.php file
    file is playing

    what is wrong???

  27. ikari Says:

    I need to be able to feed a youtube flv into my flash file. How do i do this? I have tried putting the script above into flash but it just gives me errors? So what am i doing wrong?

  28. Sylvio Ruiz Says:

    There’s no way to fecth the Youtube URL if you are embeding the swf on webpage because the “t” param has the firt quadrant of request IP encoded (in this case, the server IP used in php script). When the clients try to watch, they will receive a blank page because Youtube will check the hash generated by the server IP and will compare with the client IP (they are diferent).

  29. luciano_dev Says:

    YouTube Widget not found, never load the video

  30. Leeroy Says:

    Hello!
    Is something like http://www.youtubedisko.de possible for mobile phone browsers?

    Since we are dealing with music and poor hardware (mobile phones) I would like to ONLY load/stream the audio.

    Would such a thing be possible?
    Thanks in advance!

  31. LVN Says:

    @Mahesh,@Swami
    I am getting this
    NetStream.Play.StreamNotFound
    Pls help code:
    nc = new NetConnection();
    nc.connect(null);
    nsClient.onMetaData = ns_onMetaData;
    ns = new NetStream(nc); ns.addEventListener(NetStatusEvent.NET_STATUS,netStatusHandlr;
    ns.play(“http://www.youtube.com/get_video.php?video_id=bKzsWH0sQHs&t=vjVQa1PpcFOsubscfFLGooFMSBPcZ9POQy0FzycLZeQ=”);
    ns.client = nsClient;
    player.mx_internal::videoPlayer.attachNetStream(ns); player.mx_internal::videoPlayer.visible = true;

  32. anderson silva Says:

    With havin so much content do you ever run into any problems of plagorism or copyright violation? My blog has a lot of unique content I’ve either created myself or outsourced but it seems a lot of it is popping it up all over the web without my authorization. Do you know any solutions to help stop content from being stolen? I’d truly appreciate it.

  33. Laurent Says:

    I don’t know, maybe write uninteresting content that nobody cares about, or upload all your posts as unreadable captcha images. Then no copyright violation! 😀

Copyright © Pogopixels Ltd, 2008-2018