Asked  7 Months ago    Answers:  5   Viewed   34 times

Can anyone give me an idea how can we show or embed a YouTube video if we just have the URL or the Embed code?

 Answers

32

You have to ask users to store the 11 character code from the youtube video.

For e.g. http://www.youtube.com/watch?v=Ahg6qcgoay4

The eleven character code is : Ahg6qcgoay4

You then take this code and place it in your database. Then wherever you want to place the youtube video in your page, load the character from the database and put the following code:-

e.g. for Ahg6qcgoay4 it will be :

<object width="425" height="350" data="http://www.youtube.com/v/Ahg6qcgoay4" type="application/x-shockwave-flash"><param name="src" value="http://www.youtube.com/v/Ahg6qcgoay4" /></object>
Wednesday, March 31, 2021
 
Whakkee
answered 7 Months ago
89

I've created a simple example with Youtube video background using direct links to video stream (JS/CSS only solution). Feel free to check it on JSfiddle. Also, you can update public Google Image proxy URL to any public or your own CORS proxy.

var vid = "FUUw3zNTXH8",
    streams,
    video_tag = document.getElementById("video");

fetch("https://images"+~~(Math.random()*33)+"-focus-opensocial.googleusercontent.com/gadgets/proxy?container=none&url=https%3A%2F%2Fwww.youtube.com%2Fget_video_info%3Fvideo_id%3D" + vid).then(response => response.text()).then(function(data) {
    if (data) {
        streams = parse_youtube_meta(data);
        video_tag.src = streams['1080p'] || streams['720p'] || streams['360p'];
    } else {
        alert('Youtube API Error');
    }
});

function parse_youtube_meta(rawdata) {
    var data = parse_str(rawdata),
            player_response = JSON.parse(data.player_response),
        streams = [],
            result = {};
    
    data.player_response = player_response;
    
    if (data.hasOwnProperty('adaptive_fmts')) {
            streams = streams.concat(data.adaptive_fmts.split(',').map(function(s) {
                return parse_str(s)
            }));
        } else {
            if (player_response.streamingData && player_response.streamingData.adaptiveFormats) {
                streams = streams.concat(player_response.streamingData.adaptiveFormats);
            }
        }
        if (data.hasOwnProperty('url_encoded_fmt_stream_map')) {
            streams = streams.concat(data.url_encoded_fmt_stream_map.split(',').map(function(s) {
                return parse_str(s)
            }));
        } else {
            if (player_response.streamingData && player_response.streamingData.formats) {
                streams = streams.concat(player_response.streamingData.formats);
            }
        }
    
    streams.forEach(function(stream, n) {
        var itag = stream.itag * 1,
            quality = false,
            itag_map = {
                18: '360p',
                22: '720p',
                37: '1080p',
                38: '3072p',
                82: '360p3d',
                83: '480p3d',
                84: '720p3d',
                85: '1080p3d',
                133: '240pna',
                134: '360pna',
                135: '480pna',
                136: '720pna',
                137: '1080pna',
                264: '1440pna',
                298: '720p60',
                299: '1080p60na',
                160: '144pna',
                139: "48kbps",
                140: "128kbps",
                141: "256kbps"
            };
        //if (stream.type.indexOf('o/mp4') > 0) console.log(stream);
        if (itag_map[itag]) result[itag_map[itag]] = stream.url;
    });
    return result;
};

function parse_str(str) {
    return str.split('&').reduce(function(params, param) {
        var paramSplit = param.split('=').map(function(value) {
            return decodeURIComponent(value.replace('+', ' '));
        });
        params[paramSplit[0]] = paramSplit[1];
        return params;
    }, {});
}
html, body {
	height: 100%;
	min-height: 100%;
	background: #444;
	overflow: hidden;
}
video {
	width: 100%;
	height: 100%;
	object-fit: cover;
}
<video loop muted autoplay playsinline id="video"></video>
Friday, June 18, 2021
 
Classified
answered 4 Months ago
66

As I can't find any way to load the rtsp URL in video view (for all devices & android versions), I solved my problem with another work around. I used a webview to embed the youtube player within it, and this method working nicely in all tested devices.

Here is my code:

mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginState(PluginState.ON);
mWebView.loadUrl("http://www.youtube.com/embed/" + videoID + "?autoplay=1&vq=small");
mWebView.setWebChromeClient(new WebChromeClient());

Thank you very much for all your help guys.

Tuesday, June 29, 2021
 
Sanguine
answered 4 Months ago
36

Well, I made a simple example to do what you are looking for using the Youtube Iframe API.

Here's the jsfiddle: https://jsfiddle.net/kmsdev/gsfkL6xL/

And here's the code (see the API docs to understand it better):

Edit:

Example code updated to match OP requests. I just added an event handler to listen to tab click events. Don't forget to append &enablejsapi=1 to the iframe source url, else the API won't work. Since the idea now is a little more than just play and stop the videos by scroll, maybe this code is not the best option, but it is still a workaround.

Updated jsFiddle: https://jsfiddle.net/kmsdev/gsfkL6xL/3/

var LoadVideo = function(player_id){

    var Program = {

        Init: function(){
            this.NewPlayer();
            this.EventHandler();
        },

        NewPlayer: function(){
            var _this = this;
            this.Player = new YT.Player(player_id, {});
            _this.Player.$element = $('#' + player_id);
        },

        Play: function(){
            console.log(this.Player.IsReady);
            if( this.Player.getPlayerState() === 1 ) return;
            this.Player.playVideo();
        },

        Pause: function(){
            if( this.Player.getPlayerState() === 2 ) return;
            this.Player.pauseVideo();
        },

        ScrollControl: function(){
            if( Utils.IsElementInViewport(this.Player.$element[0]) ) this.Play();
            else this.Pause();
        },

        EventHandler: function(){
            var _this = this;
            $(window).on('scroll', function(){
                _this.ScrollControl();
            });

            $('.tab-link').on('click', function(){
                var $target = $('#' + $(this).data().tab);
                if( !!$('iframe', $target).length && $('iframe', $target).attr('id') == _this.Player.$element.attr('id') ){
                    _this.Play();
                }
            });

        }

    };

    var Utils = {

        /** @author http://stackoverflow.com/a/7557433/1684970 */
        IsElementInViewport: function(el){
            if (typeof jQuery === "function" && el instanceof jQuery) el = el[0];
            var rect = el.getBoundingClientRect();
            return (
                rect.top >= 0 &&
                rect.left >= 0 &&
                rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
                rect.right <= (window.innerWidth || document.documentElement.clientWidth)
            );
        }

    };

    Program.Init();

};

window.onload = function(){
    LoadVideo('playerA');
    LoadVideo('playerB');
};

Feel free to use and modify it for your purpose.

Saturday, August 7, 2021
 
JustSteveKing
answered 3 Months ago
61

Using iframe is the preferred and suggested way to embed youtube videos, so this is how you need to proceed. The getting started code from the YoutTube iframe API reference loads and works in both iOS (tested on iOS 7) and Android (tested on Android 4.3).

Thursday, August 12, 2021
 
xilec
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :