当您的 YouTube 频道上有直播时,接受的答案是正确的。
但是,当您不在直播时,甚至在使用 YouTube 首映时,嵌入会显示如下内容 -
嵌入链接的网站看起来很糟糕。
可以使用 YouTube API 来解决这个问题,但免费 API 调用的数量非常有限。
解决方案:网页抓取。
检查 Youtube 频道是否为 LIVE / Premiere。
在这两种情况下,视频将首先出现在频道中,并且网页源将有一个文本{"text":" watching"}(观看前请注意空格)。这将有助于获取当前的流媒体视频。
如果 YouTube 频道没有直播,请从 YouTube 频道的 RSS 源中找到最新视频并嵌入该视频。
Youtube 频道的 RSS 提要是 -
https://www.youtube.com/feeds/videos.xml?channel_id=<_YOUR_CHANNEL_ID_HERE_>&orderby=published
需要一个服务器端脚本/程序。 (Node.JS / Python / PHP)
我用过 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 );
?>
现在在 UI 中,使用 jQuery 发送和 AJAX 请求到您的服务器来获取 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;
});
});