如何使用网址永久嵌入Youtube实时聊天?

时间:2017-06-04 13:07:26

标签: javascript php url youtube embed

频道直播的嵌入网址为:

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

并且它有效但如果我想在其附近嵌入YouTube当前流媒体直播,我用于嵌入的网址是:

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

问题在于:对于每个新的直播流,视频ID都会发生变化。因此嵌入式代码不再有效,并且下次流式传输不会显示聊天。我希望永久性URL实时聊天对我的所有YouTube流式传输都有效 每次都不会手动更改视频ID。 怎么解决?也许使用PHP或javascript中的脚本来读取当前的YouTube URL并替换聊天嵌入URL中的视频ID? 感谢

2 个答案:

答案 0 :(得分:7)

您可以使用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;
}

答案 1 :(得分:2)

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

确实,其中一个用例是:

  • 关联视频流和广播。

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

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

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

相关问题