当您在YouTube频道上播放实时流时,接受的答案是正确的。
但是,当您不是实时或者即使使用YouTube Premiere时,嵌入式会显示类似于这样的内容 -
![enter image description here](https://istack.dev59.com/Sb7fs.webp)
这在嵌入链接的网站上看起来很糟糕。
为了解决这个问题,可以使用YouTube API,但免费API调用的数量非常有限。
解决方案:Web Scraping。
检查Youtube频道是否正在直播/首映。
在这两种情况下,视频将首先出现在频道中,并且网页源将具有文本{"text":" watching"}
(注意观看前的空格)。这将有助于获取当前正在流式传输的视频。
如果YouTube频道没有实时流,则从YouTube频道的RSS Feed中找到最新的视频并嵌入该视频。
Youtube频道的RSS feed将是 -
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_>';
$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)){
$contents = substr($contents, strpos($contents, $searchfor));
$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 {
$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) {
$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。
let channelID = "<_YOUR_CHANNEL_ID_HERE_>";
let iframe = document.querySelector("#my-iframe");
let ts = new Date().getTime();
$.getJSON("<SERVER>/<PHP_SCRIPT_ABOVE>.php", {_: ts}).done(function(resp) {
if(resp){
iframe.src = resp.iframeUrl;
}
}).fail(function(){
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;
});
});
<iframe width="560" height="349" src="https://www.youtube.com/embed/live_stream?channel=yourChannelid" frameborder="0" allowfullscreen></iframe>
- Clain Dsilva