问题
The embed URL for a channel's live stream is:
https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID
and it works but if I want to embed near at it a YouTube live chat for current streaming the URL that I use for the embed is:
https://www.youtube.com/live_chat?v=VIDEOID&embed_domain=DOMAINURL
The problem is this: for every new live stream the Video ID changes. So that the embedded code isn't valid anymore and chat isn't displayed for next streaming.I want a permanent URL live chat valid for all my YouTube streaming without change video id manually every time. How to resolve? Perhaps with a script in PHP or javascript that read current YouTube URL and replace video id in chat embed URL? thanks
回答1:
You could get the video ID using PHP like this:
<?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:
You should be able to use YouTube Live Streaming API to get the id and use the Live Stream data for any needs you have.
Indeed, one of the use cases is:
- Associate video streams and broadcasts.
On this page, you have a PHP example on how to "Retrieve a channel's video streams". On that code, $streamItem is a LiveStream, which contains the id of the live stream and you can leverage that.
On a related note, the API also allows you to work with LiveBroadcasts, which contains the reference snippet.liveChatId
to link it to LiveChatMessages. The latter would allow you to work with the messages in any format you want too. Perhaps, this would suit your needs better. The previous page with example codes, also has a good example on how to "Retrieve a channel's broadcasts".
I could copy the codes here, but I think the best working example is well documented on the Reference of the API :)
来源:https://stackoverflow.com/questions/44354421/how-to-embed-youtube-live-chat-with-url-permanent