【问题标题】:How to embed Youtube live chat with url permanent?如何永久嵌入带有 url 的 Youtube 实时聊天?
【发布时间】:2017-11-05 08:52:35
【问题描述】:

频道直播的嵌入网址是:

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

它可以工作,但如果我想在它附近嵌入一个 YouTube 实时聊天,用于当前流式传输,我用于嵌入的 URL 是:

https://www.youtube.com/live_chat?v=VIDEOID&embed_domain=DOMAINURL 

问题在于:对于每个新的直播,视频 ID 都会发生变化。因此嵌入的代码不再有效,并且下一次流媒体不会显示聊天。我想要一个永久 URL 实时聊天,对我的所有 YouTube 流媒体都有效 无需每次手动更改视频 ID。 如何解决?也许使用 PHP 或 javascript 中的脚本读取当前 YouTube URL 并替换聊天嵌入 URL 中的视频 ID? 谢谢

【问题讨论】:

    标签: javascript php url youtube embed


    【解决方案1】:

    您可以像这样使用 PHP 获取视频 ID:

    <?php
    
    try {
        $videoId = getLiveVideoID('CHANNEL_ID');
    
        // Output the Chat URL
        echo "The Chat URL is https://www.youtube.com/live_chat?v=".$videoId;
    } catch(Exception $e) {
        // Echo the generated error
        echo "ERROR: ".$e->getMessage();
    }
    
    // The method which finds the video ID
    function getLiveVideoID($channelId)
    {
        $videoId = null;
    
        // Fetch the livestream page
        if($data = file_get_contents('https://www.youtube.com/embed/live_stream?channel='.$channelId))
        {
            // Find the video ID in there
            if(preg_match('/\'VIDEO_ID\': \"(.*?)\"/', $data, $matches))
                $videoId = $matches[1];
            else
                throw new Exception('Couldn\'t find video ID');
        }
        else
            throw new Exception('Couldn\'t fetch data');
    
        return $videoId;
    }
    

    【讨论】:

    【解决方案2】:

    您应该能够使用YouTube Live Streaming API 获取 id 并使用直播数据来满足您的任何需求。

    确实,其中一个用例是:

    • 关联视频流和广播。

    this page,您有一个关于如何“检索频道的视频流”的 PHP 示例。在该代码中,$streamItem 是 LiveStream,其中包含直播流的 id,您可以利用它。

    在相关说明中,API 还允许您使用 LiveBroadcasts,其中包含引用 snippet.liveChatId 以将其链接到 LiveChatMessages。后者也允许您以任何您想要的格式处理消息。也许,这会更好地满足您的需求。上一页的示例代码,也有一个很好的例子来说明如何“检索频道的广播”。

    我可以在这里复制代码,但我认为最好的工作示例在 API 参考中有很好的记录:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-09
      • 2019-02-27
      • 2020-07-06
      • 1970-01-01
      • 2018-11-05
      • 2022-12-10
      • 2016-01-19
      • 2015-05-26
      相关资源
      最近更新 更多