One of my most successful open source projects is my collection of templates for Construct 3. Not so much the part dedicated to video games as the one where I experimented with integrating JavaScript and event sheets. I think it might be useful to give some tips on how to create a custom YouTube video player with JavaScript.

First, let’s see what I want to achieve:

The interface is quite simple. Most of the screen is taken up by video. At the top there is space for the title, and on the right some buttons to control playback (Play, Pause, Stop and the volume). Still on the right, but further down, some buttons allow you to choose which video to play, and possibly to select others via the YouTube ID.

It is a project designed as a demonstration, so in the code I put the ability to view YouTube videos starting from two separate JSON files. The first with the video IDs, the second with the URLs. Of course, you can choose your own preferred method.

You can also download the code from this link: simple-youtube-player.c3p.

Running the project the interface looks like this:

Let’s coding

It’s time for the most interesting part: how to use Javascript to create a simple YouTube player. First, of course, I recommend consulting the official documentation.

I need two functions to run when the page starts. With LoadAPI I import the YouTube bees into my project:

I need another function to actually create the player and assign the events that I am interested in monitoring (i.e. being able to control the execution of the video through custom buttons)

Finally I can create the actual video using the createVideo function and passing the iFrame ID as argument:

How to use this code depends on the type of project and the framework. In my example project I use this function to pass some information to the main interface:

Create custom commands

Since I have linked the YouTube player to the web page iFrame, I can create custom functions to use in my code. I can also have multiple videos on the same page, as long as they each have a different ID.

Play a video, pause it and stop it

Manage the volume of a YouTube video

Load a video but don’t play it automatically

Load a video and play it immediately

Load a playlist

Find the duration of a video

E così via.

YouTube without code

As for the JavaScript part, I think I can stop here. For those who want to look at the part inserted in the Event Sheets of the project, it is simply a matter of recalling the corresponding functions.

For example, function C3 is nothing more than this:

Similarly, to manage video playback I can use JS in a “hidden” way:

Thanks for reading