Show Youtube video source into HTML5 video tag?
Asked Answered
N

8

141

I'm trying to put a YouTube video source into the HTML5 <video> tag, but it doesn't seem to work. After some Googling, I found out that HTML5 doesn't support YouTube video URLs as a source.

Can you use HTML5 to embed YouTube videos? If not, is there any workaround?

Numbing answered 1/3, 2011 at 16:34 Comment(1)
An IFrame solution as given below by #5157877 should suffice as a workaround.Spunky
H
15

Step 1: add &html5=True to your favorite youtube url

Step 2: Find <video/> tag in source

Step 3: Add controls="controls" to video tag: <video controls="controls"..../>

Example:

<video controls="controls" class="video-stream" x-webkit-airplay="allow" data-youtube-id="N9oxmRT2YWw" src="http://v20.lscache8.c.youtube.com/videoplayback?sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Cratebypass%2Coc%3AU0hPRVRMVV9FSkNOOV9MRllD&amp;itag=43&amp;ipbits=0&amp;signature=D2BCBE2F115E68C5FF97673F1D797F3C3E3BFB99.59252109C7D2B995A8D51A461FF9A6264879948E&amp;sver=3&amp;ratebypass=yes&amp;expire=1300417200&amp;key=yt1&amp;ip=0.0.0.0&amp;id=37da319914f6616c"></video>

Note there seems to some expire stuff. I don't know how long the src string will work.

Still testing myself.

Edit (July 28, 2011): Note that this video src is specific to the browser you use to retrieve the page source. I think Youtube generates this HTML dynamically (at least currently) so in testing if I copy in Firefox this works in Firefox, but not Chrome, for example.

Hereunto answered 17/3, 2011 at 20:19 Comment(4)
The expiration and fact that it only works in a specific browser makes this solution pretty useless.Chalk
Is it capable of playing ALL youtube videos?Accompaniment
YouTube could theoretically change the underlying storage URLs for all of their videos if they'd like at any time. The URL provided in the src attribute above is probably not guaranteed to work long-term.Archiepiscopal
Yes, useful information but sounds like a bad idea. YouTube could decide to close access to the direct video link at any time.Testee
B
38

This answer does not work anymore, but I'm looking for a solution.

As of . 2015 / 02 / 24 . there is a website (youtubeinmp4) that allows you to download youtube videos in .mp4 format, you can exploit this (with some JavaScript) to get away with embedding youtube videos in <video> tags. Here is a demo of this in action.

##Pros

  • Fairly easy to implement.
  • Quite fast server response actually (it doesn't take that much to retrieve the videos).
  • Abstraction (the accepted solution, even if it worked properly, would only be applicable if you knew beforehand which videos you were going to play, this works for any user inputted url).

##Cons

  • It obviously depends on the youtubeinmp4.com servers and their way of providing a downloading link (which can be passed as a <video> source), so this answer may not be valid in the future.

  • You can't choose the video quality.


###JavaScript (after load)

videos = document.querySelectorAll("video");
for (var i = 0, l = videos.length; i < l; i++) {
    var video = videos[i];
    var src = video.src || (function () {
        var sources = video.querySelectorAll("source");
        for (var j = 0, sl = sources.length; j < sl; j++) {
            var source = sources[j];
            var type = source.type;
            var isMp4 = type.indexOf("mp4") != -1;
            if (isMp4) return source.src;
        }
        return null;
    })();
    if (src) {
        var isYoutube = src && src.match(/(?:youtu|youtube)(?:\.com|\.be)\/([\w\W]+)/i);
        if (isYoutube) {
            var id = isYoutube[1].match(/watch\?v=|[\w\W]+/gi);
            id = (id.length > 1) ? id.splice(1) : id;
            id = id.toString();
            var mp4url = "http://www.youtubeinmp4.com/redirect.php?video=";
            video.src = mp4url + id;
        }
    }
}

###Usage (Full)

<video controls="true">
        <source src="www.youtube.com/watch?v=3bGNuRtlqAQ" type="video/mp4" />
    </video>

Standard video format.

###Usage (Mini)

<video src="youtu.be/MLeIBFYY6UY" controls="true"></video>

A little less common but quite smaller, using the shortened url youtu.be as the src attribute directly in the <video> tag.

Bettinabettine answered 24/2, 2015 at 3:50 Comment(4)
Nice function and works on Mozilla and Chrome but how to set video width and height if <video> have 100% width and 200px height.Vagrom
I have implemented this solution, but 2 days later, YT blocked it. It doens't work anymore. :(Quoit
this doesn't work anymore unfortunately. It used to work great. I hope there is another solution for it!Stereochrome
This uses php to get the video url. In this case it is completely unnecessary to use anything but JavaScript in order to get the URL.Jacaranda
M
28

The <video> tag is meant to load in a video of a supported format (which may differ by browser).

YouTube embed links are not just videos, they are typically webpages that contain logic to detect what your user supports and how they can play the youtube video, using HTML5, or flash, or some other plugin based on what is available on the users PC. This is why you are having a difficult time using the video tag with youtube videos.

YouTube does offer a developer API to embed a youtube video into your page.

I made a JSFiddle as a live example: http://jsfiddle.net/zub16fgt/

And you can read more about the YouTube API here: https://developers.google.com/youtube/iframe_api_reference#Getting_Started

The Code can also be found below

In your HTML:

<div id="player"></div>

In your Javascript:

var onPlayerReady = function(event) {
    event.target.playVideo();  
};

// The first argument of YT.Player is an HTML element ID. 
// YouTube API will replace my <div id="player"> tag 
// with an iframe containing the youtube video.

var player = new YT.Player('player', {
    height: 320,
    width: 400,
    videoId : '6Dc1C77nra4',
    events : {
        'onReady' : onPlayerReady
    }
});
Mendelism answered 22/3, 2015 at 1:32 Comment(5)
I recently got this problem: The fullscreen is no longer supported on iPad! Your jsfiddle-example are perfect to illustrate: On pc it works, on iPad not. ..I guess I should ask a new question on this, but someone here maybe can comment?Cordate
@Snorvarg My answer should works on any HTML5 compliant browser, which as long as you're running a rather recent version version of iOS (10+) on your iPad it should work. If you don't need to programmatically control the video, you can try using the simple iframe embed API. You can find an example here developers.google.com/youtube/iframe_api_reference#Examples, or view vinayvasyani's answer. If you still have a problem, then I would ask a new question using the "How to Ask a Good Question" guidelines found at stackoverflow.com/help/how-to-ask.Mendelism
@Snorvarg I came across this productforums.google.com/forum/#!topic/youtube/q7cAnPlN_-Y, a similar issue occuring in Firefox and it was resolved because they needed to request full screen permissions. So I'm willing to bet that's why full screen isn't working on your iPad, which unfortunately iOS Safari doesn't appear to support. An alternate solution is to add your own full screen button and just resize the iframe player to the width/height of your screen.Mendelism
Thanks for your tips and links. I added a question a few days ago, here: #49650540 But after a while, I decided to make a fullscreen button of my own as you have proposed, and it works fine.Cordate
Great stuff, however I ran into the error "TypeError: YT.Player is not a constructor", as described here: #52062669. As the (only) answer points out, this results of the asynchronous script load and the API not yet being ready when being called. This can be avoided by implementing the onYouTubeIframeAPIReady function (and putting the last code block of above code inside it).Xavierxaviera
N
28

I have created a realtively small (4.89 KB) javascript library for this exact functionality.

Found on my GitHub here: https://github.com/thelevicole/youtube-to-html5-loader/

It's as simple as:

<video data-yt2html5="https://www.youtube.com/watch?v=ScMzIvxBSi4"></video>

<script src="https://cdn.jsdelivr.net/gh/thelevicole/[email protected]/dist/YouTubeToHtml5.js"></script>
<script>new YouTubeToHtml5();</script>

Working example here: https://jsfiddle.net/thelevicole/5g6dbpx3/1/

What the library does is extract the video ID from the data attribute and makes a request to the https://www.youtube.com/get_video_info?video_id=. It decodes the response which includes streaming information we can use to add a source to the <video> tag.


UPDATE June 2021

YouTube have recently updated their API which has broken previous versions of this package. Please now use versions 4.0.1 and up! Updated example:

<video data-yt2html5="https://www.youtube.com/watch?v=ScMzIvxBSi4"></video>

<script src="https://cdn.jsdelivr.net/gh/thelevicole/[email protected]/dist/YouTubeToHtml5.js"></script>
<script>new YouTubeToHtml5();</script>

https://jsfiddle.net/thelevicole/5g6dbpx3/2/

Novosibirsk answered 18/11, 2020 at 13:49 Comment(8)
Could you please explain how to set it up in Angular?Copolymerize
Hi @levi-cole I tried your GitHub code , but is showing me this error : prnt.sc/107j0asTarrasa
@ParthaviPatel please can you open an issue on GitHub here: github.com/thelevicole/youtube-to-html5-loader/issues thanks!Novosibirsk
It should be mentioned somewhere that this library makes requests to the author's server, yt2html.com in order to retrieve the video streaming src.Liquorice
@Liquorice correct! Versions prior to 4.0.1 were able to contact YouTubes API directly but they then implemented CORS headers preventing the data to be retrieved via Ajax. My server, however, can still successfully make the request so it acts as a very basic middle man.Novosibirsk
@LeviCole Is the server open source, or just the npm package?Lateen
i was using this yesterday and it was working but now it doesnt and i think its because YouTube wants us to use the Iframe API: developers.google.com/youtube/iframe_api_referenceStedman
TypeError: Cannot read properties of undefined (reading 'streamingData') at YouTubeToHtml5.parseYoutubeMeta (YouTubeToHtml5.js:1:4584) at YouTubeToHtml5.js:1:6023 YouTubeToHtml5.parseYoutubeMeta @ YouTubeToHtml5.js:1 (anonymous) @ YouTubeToHtml5.js:1 XMLHttpRequest.send (async) (anonymous) @ YouTubeToHtml5.js:1 YouTubeToHtml5.fetch @ YouTubeToHtml5.js:1 YouTubeToHtml5.loadSingle @ YouTubeToHtml5.js:1 (anonymous) @ YouTubeToHtml5.js:1 YouTubeToHtml5.load @ YouTubeToHtml5.js:1 YouTubeToHtml5 @ YouTubeToHtml5.js:1 (anonymous) @ ?editor_console=true:112Tui
H
15

Step 1: add &html5=True to your favorite youtube url

Step 2: Find <video/> tag in source

Step 3: Add controls="controls" to video tag: <video controls="controls"..../>

Example:

<video controls="controls" class="video-stream" x-webkit-airplay="allow" data-youtube-id="N9oxmRT2YWw" src="http://v20.lscache8.c.youtube.com/videoplayback?sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Cratebypass%2Coc%3AU0hPRVRMVV9FSkNOOV9MRllD&amp;itag=43&amp;ipbits=0&amp;signature=D2BCBE2F115E68C5FF97673F1D797F3C3E3BFB99.59252109C7D2B995A8D51A461FF9A6264879948E&amp;sver=3&amp;ratebypass=yes&amp;expire=1300417200&amp;key=yt1&amp;ip=0.0.0.0&amp;id=37da319914f6616c"></video>

Note there seems to some expire stuff. I don't know how long the src string will work.

Still testing myself.

Edit (July 28, 2011): Note that this video src is specific to the browser you use to retrieve the page source. I think Youtube generates this HTML dynamically (at least currently) so in testing if I copy in Firefox this works in Firefox, but not Chrome, for example.

Hereunto answered 17/3, 2011 at 20:19 Comment(4)
The expiration and fact that it only works in a specific browser makes this solution pretty useless.Chalk
Is it capable of playing ALL youtube videos?Accompaniment
YouTube could theoretically change the underlying storage URLs for all of their videos if they'd like at any time. The URL provided in the src attribute above is probably not guaranteed to work long-term.Archiepiscopal
Yes, useful information but sounds like a bad idea. YouTube could decide to close access to the direct video link at any time.Testee
U
-4

how about doing it the way hooktube does it? they don't actually use the video URL for the html5 element, but the google video redirector url that calls upon that video. check out here's how they present some despacito random video...

<video id="player-obj" controls="" src="https://redirector.googlevideo.com/videoplayback?ratebypass=yes&amp;mt=1510077993----SKIPPED----amp;utmg=ytap1,,hd720"><source>Your browser does not support HTML5 video.</video>

the code is for the following video page https://hooktube.com/watch?v=72UO0v5ESUo

youtube to mp3 on the other hand has turned into extremely monetized monster that returns now download.html on half of video download requests... annoying...

the 2 links in this answer are to my personal experiences with both resources. how hooktube is nice and fresh and actually helps avoid censorship and geo restrictions.. check it out, it's pretty cool. and youtubeinmp4 is a popup monster now known as ConvertInMp4...

Ufa answered 7/11, 2017 at 18:18 Comment(1)
You don't need to use an external service, just JavaScript. You can get the URL if you parse youtube's get_video_info page.Jacaranda
A
-4

In case anyone stumbles upon this question, a neat way to embed YouTube video is to use embed tag, like so: <embed src="https://www.youtube-nocookie.com/embed/DelkRGZCtTs" width="100%" height="333">

Auschwitz answered 8/4, 2021 at 21:43 Comment(0)
O
-7

The easiest answer is given by W3schools. https://www.w3schools.com/html/html_youtube.asp

  1. Upload your video to Youtube
  2. Note the Video ID
  3. Now write this code in your HTML5.
<iframe width="640" height="520"
src="https://www.youtube.com/embed/<VideoID>">
</iframe>
Overcast answered 12/8, 2020 at 11:43 Comment(1)
The question asks about the <video> tag, not <iframe>.Intersidereal
R
-13

With the new iframe tag embedded in your website, the code will automatically detect whether you are using a browser that supports HTML5 or not.

The iframe code for embedding YouTube videos is as follows, simply copy the Video ID and replace in the code below:

<iframe type="text/html" 
    width="640" 
    height="385" 
    src="http://www.youtube.com/embed/VIDEO_ID"
    frameborder="0">
</iframe>
Roundsman answered 17/3, 2011 at 20:56 Comment(5)
"New" iframe tag? iframe has been around for ages…Evzone
This is not a solution to the answer, it clearly states video tag and not iframe...Sapor
Maybe the OP just didn't know about the existence of the iframe tag and that's why he directly asked about the video tag. Otherwise he wouldn't have asked if HTML5 (generically) supports Youtube videos, but he would have restricted the question to the video tag. He even asked "is there any workaround for that?" in his last sentence, so this answer is perfectly valid.Aman
To embed youtube.com videos in my blogger.com blog, iframe is the only convenient solution. On top of that, the embed code that youtube.com generates is an iframe tag. Also, w3schools.com recommends iframes: http://www.w3schools.com/html/html_youtube.asp. Where the video tag is not mentioned.Message
Just in case if anyone is curious... The issue is using a video tag is not the proper approach for YouTube videos because the public URLs to embed YouTube videos aren't an actual media resource. That is why there are people suggesting using iframes. Trying to use a video tag will mean you will be using private URLs that may change in the future. It is like attempting to access a private member in an object-oriented language. You can view YouTube's official documentation here developers.google.com/youtube/iframe_api_reference#ExamplesMendelism

© 2022 - 2024 — McMap. All rights reserved.