如何嵌入新的YouTube直播视频永久链接?

40

我经常在YouTube上直播,但自从昨天以来,出现了奇怪的问题:

我在网站中嵌入了直播链接,它是youtube.com/embed/ABCDE(普通的嵌入链接)。该链接过去会显示当前的直播而不是特定的视频。例如:

我正在直播,您可以在youtube.com/embed/ABCDE上观看。当我完成时,视频将获得自己的URL,类似于youtube.com/watch?v=FGHIJ。在下一次直播时,用户可以在youtube.com/embed/ABCDE上观看(这是一个不变的永久链接)。

现在,每次我直播时,直播都会有自己的链接,这意味着我必须手动更新我的嵌入代码。

我在Google、SO和YouTube上进行了一些研究,发现直播的永久链接为youtube.com/channel/CHANNEL_ID/live。这很棒,但我找不到嵌入它的方法。

(我使用WordPress,但我没有找到任何插件可以自动完成这个功能)。

TL:DR;如何在页面youtube.com/channel/CHANNEL_ID/live中嵌入直播?

6个回答

79

2
这段代码截至2017年12月运行良好。同志们辛苦了,完整的嵌入代码如下:<iframe width="560" height="349" src="https://www.youtube.com/embed/live_stream?channel=yourChannelid" frameborder="0" allowfullscreen></iframe> - Clain Dsilva
今天看到了这个,对我帮助很大,谢谢。我需要嵌入另一个频道(不是我的),对于那些需要类似操作的人,在这里可以找到该频道的ID - https://commentpicker.com/youtube-channel-id.php - KDT
2
注意:为了使其正常工作(截至2018年10月20日左右),直播流的可见性必须设置为“公共”。 - jaraics
1
奇怪的是,这个链接只能用一次。在我结束直播并开始新的直播后,这个链接总是会显示一个播放器窗口,上面写着“直播已停止”。(截至2019年7月15日) - shenkwen
正如@jaraics所提到的,除非您将视频设置为公开,否则此方法无法生效。此外,这是一个关于嵌入YouTube直播聊天的有趣相关问题:https://dev59.com/y1cP5IYBdhLWcg3weJxR - Ryan
显示剩余2条评论

9
问题有两个方面:
  1. WordPress重新格式化了YouTube链接
  2. 您需要一个自定义的嵌入链接来支持直播嵌入
作为先决条件(截至2016年8月),您需要链接AdSense账户,然后在您的YouTube频道中启用货币化。这是一个痛苦的变化,它破坏了很多直播流。
您需要使用以下URL格式进行嵌入:
<iframe width="560" height="315" src="https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID&autoplay=1" frameborder="0" allowfullscreen></iframe>

&autoplay=1并不是必须的,但我喜欢加上它。将CHANNEL更改为您的频道ID。需要注意的一点是,WordPress可能会在提交更改后重新格式化URL。因此,您需要一个允许您使用原始代码而不被覆盖的插件。使用自定义PHP代码插件可以帮助您,您只需像这样回显代码:

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

如果这对你有用,请让我知道!


0

你试过一个叫做“Youtube直播自动嵌入”的插件吗?

它似乎可以正常工作。试试看吧。


1
是的,它只是显示一个错误。我在“阅读更多”中有这个链接 https://support.google.com/youtube/?p=player_error1 - Itay Ganor

0

以下是如何在Squarespace中使用嵌入块类来创建响应式的方法。

将以下代码放入代码块中:

<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>

按照您的喜好进行微调!


0

当您在YouTube频道上播放实时流时,接受的答案是正确的。

但是,当您不是实时或者即使使用YouTube Premiere时,嵌入式会显示类似于这样的内容 - enter image description here

这在嵌入链接的网站上看起来很糟糕。

为了解决这个问题,可以使用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_>'; 
  
    //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;
    });
});


FYI,它是 __scraping__(和 __scrape__,__scraped__,__scraper__),而不是 scrapping。 - DisappointedByUnaccountableMod
@barny,主要目的是分享代码,感谢您的纠正! - Sherwin Varghese

0
你可以通过以下三个步骤解决这个问题(不包括channel_id):
a) 在当前格式中获取频道URL。
http://youtube/com/@channel-name/live

b) 去掉回应并找到片段:
<link rel="canonical" href="https://www.youtube.com/watch?v=

如果找不到,这意味着该频道目前没有直播(将返回频道的主页)。
如果找到了,在“v=”和关闭标签‘">'之间检索值。
获取检索到的视频ID并将其放入YouTube的嵌入式链接中。
https://youtube.com/embed/<<video_id>>?autoplay=1

在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;  
}       

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接