Titanium 7
Titanium 7

Reputation: 68

Retrieve YouTube live_stats concurrent viewers from channel instead of specific live event video

I know that it is possible to get the number of concurrent viewers for a specific live streaming YouTube event with this link: https://www.youtube.com/live_stats?v={videoid}

I was wondering if is it possible to get the live_stats for a channel or playlist instead of a specific live event.

I want to embed this data in a webpage that will have multiple different live events occurring weekly. Changing the video id for each event will be a burden. If this can't be done directly, is there a way to get the video id of a current live event from a channel and use java script or php to replace the id in the link? Please help me figure this out.

Upvotes: 1

Views: 2184

Answers (1)

Titanium 7
Titanium 7

Reputation: 68

After some time, I figured this out myself...

I created a PHP script that retrieves the video id of the first video in a playlist and puts the id into the live stats link. I take the link of live events and put them into a playlist for easy use.

<?php
// Retrieves video info from Youtube playlist. Just update [PLAYLIST_ID] and [API_KEY]
$json_url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=1&playlistId=[PLAYLIST_ID]&fields=items%2Fsnippet%2FresourceId%2FvideoId&key=[API_KEY]";
$json = file_get_contents($json_url);
$json=str_replace('},

]',"}

]",$json);
$data = json_decode($json, true);

$videoId = $data['items'][0]['snippet']['resourceId']['videoId'];

$viewers = file_get_contents("https://www.youtube.com/live_stats?v=$videoId");
echo $viewers;
?>

I then created an HTML page where the data is dynamically updated using jQuery.

<html>
<body>
<div id="status" style="color: #666; line-height: 24px; font-size: 19px; font-weight: normal; font: 19px Roboto,arial,sans-serif;"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function update() {
    $.ajax({
        url: 'viewers.php',
        dataType: 'text',
        success: function(data) {
            if (parseInt(data) == 0) {
                $("#status").css({ display: "none" });
            } else {
                $("#status").text(parseInt(data) + ' watching now' );
            }
        }
    })
}
update();
var statusIntervalId = window.setInterval(update, 5000);
</script>
</body>
</html>

This is how far I got. Now I am just wondering if there is a better way to combine these codes together to create less server requests. Each jQuery request happens every 5 seconds and is approximately 240 bytes is size. Even though the requests are small, they might still slow down a page.

If you can, please help me improve my solution. Thank you in advance.

Upvotes: 0

Related Questions