Browsed by
Tag: YouTube

YouTube OpenDay Live Feed

YouTube OpenDay Live Feed

Due to the unprecedented circumstances this year the College had to host their Open Day virtually.

We wanted to have a live feed of heads of departments answering questions which we got during the feed and beforehand. Because we wanted this front and centre we had to look into a way of embedding the feed into our dedicated Open Day webpage.

After looking around online I came across this interesting discussion on embedding Live YouTube Feeds and used it as a basis to create my own class.

https://stackoverflow.com/questions/44354421/how-to-embed-youtube-live-chat-with-url-permanent

<?php 
/*****************************************************************
	Class : LIVE EVENT SCHEDULER 
	
	This class handles the live event schedule and loads the 
	youtube live feed if an event is due.
	
	FUNCTIONS
	---------------------------------------------------------
	1. showAll()
		show all scheduled events as cards below the main feed
	2. getNextEvent()
		get an array of the next event's details
	3. showAllUpcoming()
		display a mini feed of all the upcoming events.
	4. showAllPast()
	5. getLiveChatURL()
	6. getLiveVideoID($channelId)
	7. fetchVideoFeeds()
	
*****************************************************************/
class Schedule {
	
	public $schedule = array(
	    array(
			'datetime'	=> '202006121100',
			'show'		=> false, // show in main schedule
			'subject'	=> 'Welcome Message',
			'speaker'	=> 'Principal & Vice Principal ',
			'img'		=> '',
			'vid'		=> '',
			'desc'		=> 'Welcome message from the Principal.',
			'link'		=> array( 
						array(	'link' => '', 						'text' => 'Find out more' )),
		),

	);
	
	// Properties
	public $date;
	public $time;
	public $speaker;
	public $subject;
	
	function __construct() {
		
	}
	
	/****************************************
	show all upcoming scheduled items. 
	These appear as cards below the main feed.
	
	@RETURNS
	$html (string) 	: Compiled HTML
	
	****************************************/
	public function showAll() {
		
                // Display code goes here.....
		
		return $html;
	}
	
	/*********************************************
		
		Get the next event
		This was used to help calculate when the next event was.
		
		@RETURNS
		$return (array)	: The event array that is next up.
		
	*********************************************/
	public function getNextEvent() {
		$now 	= date_create(); // get current date and time. 
		$compare 	= date_format($now,"YmdHis"); // formatted current date and time to use as a comparison
		$return 	= $this->schedule[0]; // The event array that is next up. (default as first)
		
		// loop through events and compare with formatted date. 
		foreach($this->schedule as $event) {
			
			if($compare < $event['datetime'].'00') {
				$return = $event;
				break;
			}
		}
		
		return $return; 
	} 
	
	/***************************************************
		Show all upcoming events as a mini feed
		
		@RETURNS
		$html (string) : Container for the compiled HTML
	***************************************************/
	public function showAllUpcoming() {

		// Display code goes here ....
		
		return $html;
	}
	
	/***********************************************
		Show all past events
		added so that past videos could be viewed.
		
		@RETURNS
		$html (string) : Compiled HTML of past events. 
		
	***********************************************/
	public function showAllPast() {
		// Display Code goes here....
		
		return $html;
	}
	
	/********************************************
		Fetch Live Chat URL from YouTube Channel
		This requires a YouTube Channel ID.
		
		It will try to fetch the current live video feed ID 
		present on that Youtube Channel. 
		If it can't find any Live Feeds will return an error. 
		If it can the live chat feed url is returned. 
	*********************************************/
	public function getLiveChatURL() {
			
		try {
		    $livevideoId = $this->getLiveVideoID('<< REPLACE WITH CHANNEL ID >>');
		
		    // Output the Chat URL
		    //echo "The Chat URL is https://www.youtube.com/live_chat?v=".$livevideoId;
		    return array( true, "https://www.youtube.com/live_chat?v=".$livevideoId);
		} catch(Exception $e) {
			
			
		    // Echo the generated error
		    return array( false, "1. ERROR: ".$e->getMessage());
		}
	}
	
	// The method which finds the video ID
	public function getLiveVideoID($channelId)
	{
	    $livevideoId = 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('2. Couldn\'t find video ID');
	    }
	    else
	        throw new Exception('3. Couldn\'t fetch data');
	
	    return $videoId;
	}
	
	// AJax function.
	public function fetchVideoFeeds() {
		$html = '';
		$result = $this->getLiveChatURL();
		
		$html .= '<div class="col-xs-12 col-lg-8">';
					//$html .= '<pre>Dev Note : We are testing the live stream right now</pre><iframe style="width: 100%; height: 411px;" src="https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID_HERE&autoplay=1&rel=0&showinfo=0&cc_load_policy=1" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen autoplay></iframe>';

					if($result[0] == true) {
						$html .= '<iframe title="VIDEO FEED TITLE" aria-label="VIDEO ARIA LABEL" style="width: 100%; height: 411px;" src="https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID_HERE&autoplay=1&rel=0&showinfo=0&cc_load_policy=1" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen autoplay></iframe>';
					} else {
						$html .= '<iframe title="VIDEO TITLE" aria-label="VIDEO ARIA LABEL" style="width: 100%; height: 411px;" src="https://www.youtube-nocookie.com/embed/ZvzgjA5hhdo?rel=0&autoplay=0&rel=0&showinfo=0&cc_load_policy=1" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';
					} 
				$html .= '</div>
				<div class="col-xs-12 col-lg-4">';
				
					if($result[0] == true) {
						$html .= '<iframe src="'.$result[1].'&embed_domain=www.YOURDOMAIN.ac.uk" style="width: 100%; height: 411px" frameborder="0"></iframe>';
					} else {
						$html .= '<div class="nofeed">';
							$html .= '<h2 class="arrow">Upcoming Events </h2>';
							$nextEvent = $this->getNextEvent();
							$datetime = date_create($nextEvent['datetime']);
							$today = date_create();
							$dateDiff = date_diff($today,$datetime);
							
							$html .= '<div class="content">';
								$html .= '<div class="countdown">';
									$html .= '<div style="display: none;">'.($dateDiff->d > 0 ? $dateDiff->d.'d ' : '').(($dateDiff->d > 0 || $dateDiff->h) > 0 ? $dateDiff->h.'h ' : ''). (($dateDiff->h || $dateDiff->i > 0) ? $dateDiff->i.'m ' : '').$dateDiff->s.'s</div>';
									$html .= '<h6>The next event will be in <time class="counter" datetime="'.date_format($datetime,'Y-m-d\TH:i:s\Z').'" data-now="'.date_format($today, 'Y-m-d\TH:i:s\Z').'">'.($dateDiff->d > 0 ? $dateDiff->d.'d ' : '').(($dateDiff->d > 0 || $dateDiff->h) > 0 ? $dateDiff->h.'h ' : ''). (($dateDiff->h || $dateDiff->i > 0) ? $dateDiff->i.'m ' : '').$dateDiff->s.'s</time></h6>';
									$html .= $this->showAllUpcoming(); 
																		
								$html .= '</div>'; 
								
							$html .= '</div>';
						$html .= '</div>';
					} 
				$html .= '</div>';
				
		return $html;
	}
}

// init
$schedule = new Schedule(); 
?>

(I’ve taken out some of the irrelevant display bits).

The Schedule

For this example I have the schedule as an array but really it would be better to use a database and add some fetch from database functions to the class.

showAll(), showAllUpcoming(),showAllPast()

These functions just displayed all the upcoming events below the feed and aren’t important for this post.

getNextEvent()

We had a little countdown running on the page to the next event this function was just to help with that countdown and not important for this post.

getLiveChatURL()

This function tries to fetch the Live Chat url if it fails it will return an error message.

$livevideoId = $this->getLiveVideoID('PASTE CHANNEL URL HERE');

To get the Live Chat URL we also need the Live Video ID. This is fetched via the next function getLiveVideoID() . It requires the Channel ID to get this.

Getting the Channel ID

It’s actually fairly straightforward to get the Channel ID. You can either get this from your channel settings or you can simply go to your channel and the ID will display at the end of your URL.

Screenshot of YouTube Channel URL - the ID is the string of characters after /channel/
the ID is the string of characters after /channel/

Note About YouTube Requirements

Please note there are a few requirements regarding embedding Live Video Feeds.

  1. To stream direct to Youtube feeds must be public and allow embedding for the script to work.
  2. You need a certain number of subscribers (1000+) and be eligible for the YouTube Partner Program to be able to embed youtube feeds on your websites directly.
  3. Had we known! Restream.io costs but you can go live on multiple platforms at once (Twitter/Twitch/Facebook/Instagram) and embed on any website you like. ( thanks Steve 🙂 )
return array( true, "https://www.youtube.com/live_chat?v=".$livevideoId);

The Live Chat Feed for any Live Video will follow the above format. Of course this might change in the future with YouTube updates but this works at time of writing.

/********************************************
		Fetch Live Chat URL from YouTube Channel
		This requires a YouTube Channel ID.
		
		It will try to fetch the current live video feed ID 
		present on that Youtube Channel. 
		If it can't find any Live Feeds will return an error. 
		If it can the live chat feed url is returned. 
	*********************************************/
	public function getLiveChatURL() {
			
		try {
		    $livevideoId = $this->getLiveVideoID('PASTE CHANNEL ID HERE');
		
		    // Output the Chat URL
		    //echo "The Chat URL is https://www.youtube.com/live_chat?v=".$livevideoId;
		    return array( true, "https://www.youtube.com/live_chat?v=".$livevideoId);
		} catch(Exception $e) {
			
			
		    // Echo the generated error
		    return array( false, "1. ERROR: ".$e->getMessage());
		}
	}

getLiveVideoID($channelId)

This function gets the ID of the Live Video using the provided Channel ID.

if($data = file_get_contents('https://www.youtube.com/embed/live_stream?channel='.$channelId))

Currently the Stream url will follow the above format. Of course this might change in the future with YouTube updated but this works at time of writing.

if(preg_match('/\'VIDEO_ID\': \"(.*?)\"/', $data, $matches))
	$videoId = $matches[1];
else
	 throw new Exception('2. Couldn\'t find video ID');

The script then searches the returned file contents for the ‘VIDEO_ID’ variable which is printed in the javaScript on that url.

^ There may be another way of doing this via YouTube’s Javascript Api but this does work.

// The method which finds the video ID
	public function getLiveVideoID($channelId)
	{
	    $livevideoId = 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('2. Couldn\'t find video ID');
	    }
	    else
	        throw new Exception('3. Couldn\'t fetch data');
	
	    return $videoId;
	}

fetchVideoFeeds()

Finally I added a function to display the final feed or schedule if there was no live feed. This can also be requested via Ajax to update the feed automatically once the countdown has been reached.

$result = $this->getLiveChatURL();

First, this function gets the current Live Chat result from the above function. If there’s no result from this e.g. an error the script instead shows an advert for the college and a schedule of upcoming Live Events.

Screenshot of the alternative video and schedule of live events.
Screenshot of the upcoming Events Schedule.

If there is a result the script replaces the video advert with the live feed…

if($result[0] == true) {
	$html .= '<iframe title="VIDEO TITLE HERE" aria-label="VIDEO ARIA LABEL" style="width: 100%; height: 411px;" src="https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID_HERE&autoplay=1&rel=0&showinfo=0&cc_load_policy=1" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen autoplay></iframe>';
}

Note : I should probably update this so that the Live Stream url is inserted by the schedule class.

if($result[0] == true) {
	$html .= '<iframe src="'.$result[1].'&embed_domain=www.dumgal.ac.uk" style="width: 100%; height: 411px" frameborder="0"></iframe>';
}

It also adds in the Live Chat embed. Note the &embed_domain variable. This should be set to your websites url otherwise the video will not show.

$nextEvent = $this->getNextEvent();
							$datetime = date_create($nextEvent['datetime']);
							$today = date_create();
							$dateDiff = date_diff($today,$datetime);
							
							$html .= '<div class="content">';
								$html .= '<div class="countdown">';
									$html .= '<div style="display: none;">'.($dateDiff->d > 0 ? $dateDiff->d.'d ' : '').(($dateDiff->d > 0 || $dateDiff->h) > 0 ? $dateDiff->h.'h ' : ''). (($dateDiff->h || $dateDiff->i > 0) ? $dateDiff->i.'m ' : '').$dateDiff->s.'s</div>';
									$html .= '<h6>The next event will be in <time class="counter" datetime="'.date_format($datetime,'Y-m-d\TH:i:s\Z').'" data-now="'.date_format($today, 'Y-m-d\TH:i:s\Z').'">'.($dateDiff->d > 0 ? $dateDiff->d.'d ' : '').(($dateDiff->d > 0 || $dateDiff->h) > 0 ? $dateDiff->h.'h ' : ''). (($dateDiff->h || $dateDiff->i > 0) ? $dateDiff->i.'m ' : '').$dateDiff->s.'s</time></h6>';
									
									$html .= $this->showAllUpcoming(); 

I also added in a little countdown which is updated by javaScript.

All this html is then returned by the function.

Initialising the Class

// init
$schedule = new Schedule(); 

Final part of the class.php file it creates a new instance of the class.

The Open Day Page

On the open day page where the feed is to be displayed I included the new class file.

<?php 
			
// Include the Event Scheduler Class. (handles the schedules and live video links)
include('classes/class_schedule.php');
	
?>	

And added in an area for the Live Feed to go…

<!-- LIVE VIDEO FEEDS & CHAT -->
<a class="pastevents" href="#eventspast" title="View Past Events" aria-label="View Past Events">Watch Past Events</a>
<div id="videofeed" class="row videofeeds">
	<?php echo $schedule->fetchVideoFeeds(); ?>
</div>
<!-- END OF LIVE VIDEO FEEDS AND CHAT -->

JavaScript Countdown

I also added in a little bit of javaScript that updates the countdown and reloads the feed area once the countdown hits 0.

jQuery(document).ready( function($) {
	
	// Set the date we're counting down to
	var nextEventDate = $('.counter').attr('datetime');
	var today = $('.counter').data('now');
	var countDownDate = new Date(nextEventDate).getTime(); 
	
	// Update the count down every 1 second
	var x = setInterval(function() {
	
	  // Get today's date and time
	  var today = new Date();
	  // DST
	  today.setHours(today.getHours() + 1);
	  
	  var now = today.getTime();
	
	  // Find the distance between now and the count down date
	  var distance = countDownDate - now;
	
	  // Time calculations for days, hours, minutes and seconds
	  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
	  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
	  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
	  var seconds = Math.floor((distance % (1000 * 60)) / 1000);
	
	  // Display the result in the element with id="demo"
	  $('.counter').html((days > 0 ? days + "d " : '') + ((days > 0 || hours > 0) ? hours + "h " : '') + ((hours > 0 || minutes > 0) ? minutes + "m " : '') + seconds + "s ");
	
	  // If the count down is finished, write some text
	  if (distance < 0) {
	    clearInterval(x);
	    $('.counter').html('Now....reloading in <span class="reloadcount">3</span>');
			    
		// fetch the feed...
		$.get("fetch.php", function(data, status){
			$('.videofeeds').html(data); //.animate({'opacity' : '1'}); // fade back in. 
		});  
	  }
	}, 1000);    //testing    
	
});

Notes about Feed Refresh

There is roughly a minute delay between when you start your Live Feed and it appearing on YouTube so it’s a good idea to have a buffer time and start the Live Feed before the event is scheduled. This also mitigates any issues with server times being slightly out of sync.

We had a 15 minute buffer period before each event.

fetch.php

The fetch.php file just includes the schedule class and echos out the feed.

<?php 		
// Include the Event Scheduler Class. (handles the schedules and live video links)
include('classes/class_schedule.php');

echo $schedule->fetchVideoFeeds();

?>