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](https://i.stack.imgur.com/Sb7fs.png)
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;
});
});