Skip to content
Advertisement

How to embed Youtube live chat with url permanent?

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

Advertisement

Answer

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;
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement