Itay Ganor
Itay Ganor

Reputation: 4205

How to embed new Youtube's live video permanent URL?

I stream live on youtube a lot and since yesterday I experience a weird thing:

I embedded the livestream URL in my site. it was youtube.com/embed/ABCDE (normal embed link). That link used to show the current livestream and not a specific video. for example:

I'm streaming and you can watch it on youtube.com/embed/ABCDE. When i'm finished, the video gets its own url, something like youtube.com/watch?v=FGHIJ. In the next time I will stream, users can watch the stream on youtube.com/embed/ABCDE (that was a permanent url that didn't change).

Now, every time I stream, the livestream get its own link at first place, which means I have to update my embed code manually every time I stream.

I researched a bit around Google, SO and YouTube and I found out that a livestream's permanent url is youtube.com/channel/CHANNEL_ID/live. It's awesome and all, but I can't find a way to embed it.

(I use wordpress and I didn't find any plugin to do it automatically for me).

TL:DR; how to embed the livestream in the page youtube.com/channel/CHANNEL_ID/live?

Upvotes: 42

Views: 134373

Answers (6)

Gerson Rodrigues
Gerson Rodrigues

Reputation: 11

You can solve this question in 3 steps (without channel_id):

a) Retrieve the channel URL in the current format

http://youtube/com/@channel-name/live

b) Srap the response and find the snippet:

<link rel="canonical" href="https://www.youtube.com/watch?v=

If not found, it means that the channel does not have a live stream at the moment (it will return the channel's home page).

if found, retrieve the value between the 'v=' and the '">' that closes the tag.

c) Get the retrieved video_id and put it in YouTube's embedded:

https://youtube.com/embed/<<video_id>>?autoplay=1

In Java:

public String getYTLiveStreamVideoId(String channelURL) {
    StringBuilder content = new StringBuilder();  
    // Use try and catch to avoid the exceptions  
    try  
    {  
        URL url = new URL(channelURL);   
        URLConnection urlConnection = url.openConnection();   

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));  
        String line;  
        // reading from the urlconnection using the bufferedreader  
        while ((line = bufferedReader.readLine()) != null)  
        {  
            content.append(line + "\n");  
        }  
        bufferedReader.close();  
    }  
    catch(Exception e)  
    {  
        return "";
    }
    String videoId = "";  
    
    int pos = content.indexOf("link rel=\"canonical\" href=\"https://www.youtube.com/watch?v=");
    if (pos != -1) {
        videoId = content.substring(pos + 59, pos + 80);
        int pos2 = videoId.indexOf("\">");
        videoId = videoId.substring(0, pos2);
    }

    return videoId;  
}       

Upvotes: 0

Sherwin Varghese
Sherwin Varghese

Reputation: 679

The accepted answer is true when you have a LIVE stream showing on your YouTube channel.

But when you are not LIVE or even while using YouTube Premiere, the embed would show something like this - enter image description here

It looks bad on the website embedding the link.

To get around with this YouTube APIs can be used, but the number of free API calls are very limited.

Solution: Web Scraping. Check if the Youtube channel is LIVE / Premiere. In either of these cases, the video would show up first in the channel and the web page source would have a text {"text":" watching"} (notice the space before watching). This would help in obtaining the currently streaming video.

If the YouTube channel is not streaming LIVE, find the latest video from the RSS Feed of the YouTube channel and embed that video. The RSS feed of the Youtube channel would be - https://www.youtube.com/feeds/videos.xml?channel_id=<_YOUR_CHANNEL_ID_HERE_>&orderby=published

A server side script / program would be needed. (Node.JS / Python / PHP)

I have used PHP.

<?php   
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
    $channel_id = '<_YOUR_CHANNEL_ID_HERE_>'; 
  
    //Option 1 - Check if YouTube is streaming LIVE
    //Web scraping to check if we are LIVE on YouTube
    $contents = file_get_contents('https://www.youtube.com/channel/'.$channel_id);

    $searchfor = '{"text":" watching"}';
    $pattern = preg_quote($searchfor, '/');
    $pattern = "/^.*$pattern.*\$/m";
    if(preg_match_all($pattern, $contents, $matches)){
      //truncate $contents so that the match can be found easily.
      $contents = substr($contents, strpos($contents, $searchfor));  

      //If the video is LIVE or Premiering, fetch the video id.
      $search_video_id = '{"url":"/watch?v=';
      $video_pattern = preg_quote($search_video_id, '/');
      $video_pattern = "~$video_pattern\K([A-Za-z0-9_\-]{11})~";
      preg_match($video_pattern, $contents, $video_ids);

      $data = [ 'status' => 200, 
                'isLive' => true, 
                'iframeUrl' => 'https://www.youtube.com/embed/'.$video_ids[0]
              ];
    } else {    

        //Option 2 - Get the RSS YouTube Feed and the latest video from it

        $youtube = file_get_contents('https://www.youtube.com/feeds/videos.xml?channel_id='.$channel_id.'&orderby=published');
        $xml = simplexml_load_string($youtube, "SimpleXMLElement", LIBXML_NOCDATA);

        $json = json_encode($xml);
        $youtube = json_decode($json, true);
        
        foreach ($youtube['entry'] as $k => $v) {//get the latest video id
            $link = $v['link']['@attributes']['href'];
            $pos = strrpos($link, '=');
            $id = substr($link, $pos+1, strlen($link)-$pos);
            break;
        } 
        $data = [ 'status' => 200, 
                'isLive' => false,
                'iframeUrl' => 'https://youtube.com/embed/'.$id
              ];
    }
    echo json_encode( $data, JSON_UNESCAPED_SLASHES );
?>  

Now in the UI, using jQuery send and AJAX request to your server to fetch the iframe URL.

// Check if YouTube LIVE is active, if not point to the latest video
let channelID = "<_YOUR_CHANNEL_ID_HERE_>";
let iframe = document.querySelector("#my-iframe"); //get the iframe element.
let ts = new Date().getTime();

$.getJSON("<SERVER>/<PHP_SCRIPT_ABOVE>.php", {_: ts}).done(function(resp) {
  if(resp){
    iframe.src = resp.iframeUrl;
  } 
}).fail(function(){ 
    //fall back             
    let reqURL = "https://www.youtube.com/feeds/videos.xml?channel_id=";
    let ts = new Date().getTime();
    $.getJSON("https://api.rss2json.com/v1/api.json?rss_url=" + encodeURIComponent(reqURL)+channelID, {_: ts}).done( function(data) {
        let link = data.items[0].link;
        let id = link.substr(link.indexOf("=")+1);
        
        iframe.src = "https://youtube.com/embed/"+id;
    });
});

Upvotes: 1

reesericci
reesericci

Reputation: 132

Here's how to do it in Squarespace using the embed block classes to create responsiveness.

Put this into a code block:

<div class="sqs-block embed-block sqs-block-embed" data-block-type="22" >
    <div class="sqs-block-content"><div class="intrinsic" style="max-width:100%">
        <div class="embed-block-wrapper embed-block-provider-YouTube" style="padding-bottom:56.20609%;">
            <iframe allow="autoplay; fullscreen" scrolling="no" data-image-dimensions="854x480" allowfullscreen="true" src="https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID_HERE" width="854" data-embed="true" frameborder="0" title="YouTube embed" class="embedly-embed" height="480">
            </iframe>
        </div>
    </div>
</div>

Tweak however you'd like!

Upvotes: 0

Ahmed Sagarwala
Ahmed Sagarwala

Reputation: 410

The issue is two-fold:

  1. WordPress reformats the YouTube link
  2. You need a custom embed link to support a live stream embed

As a prerequisite (as of August, 2016), you need to link an AdSense account and then turn on monetization in your YouTube channel. It's a painful change that broke a lot of live streams.

You will need to use the following URL format for the embed:

<iframe width="560" height="315" src="https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID&autoplay=1" frameborder="0" allowfullscreen></iframe>

The &autoplay=1 is not necessary, but I like to include it. Change CHANNEL to your channel's ID. One thing to note is that WordPress may reformat the URL once you commit your change. Therefore, you'll need a plugin that allows you to use raw code and not have it override. Using a custom PHP code plugin can help and you would just echo the code like so:

<?php echo '<iframe width="560" height="315" src="https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID&autoplay=1" frameborder="0" allowfullscreen></iframe>'; ?>

Let me know if that worked for you!

Upvotes: 10

audiomason
audiomason

Reputation: 2413

The embed URL for a channel's live stream is:

https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID

You can find your CHANNEL_ID at https://www.youtube.com/account_advanced

Upvotes: 82

KamleshNishad
KamleshNishad

Reputation: 24

Have you tried plugin called " Youtube Live Stream Auto Embed"

Its seems to be working. Check it once.

Upvotes: -1

Related Questions