Introduction

There is no game if there is no music, and so with such knowledge, we have utilized the powers of the Youtube API to give us music. Sounds simple? Well, looking at it now, it is, but when we were originally figuring everything out, it sure wasn’t. This will serve as your guide to setting up music or just plain youtube videos for your website, so you won’t struggle as much as we did.

Keep in mind, we are basing this tutorial as if it were made purely for video, so if this isn’t your goal, you will have to slightly adjust.

HTML Setup

For the video to actually load, and to actually give the user options for changing the music and customizing their experience, we have to add these things to HTML.

<div>
  <!--Loads Youtube Video-->
  <div id="player"></div>

    <!--HTML for Buttons-->
    <button onclick="input()" id="swapInput">Change Music</button>
    <button onclick="mute()" id="muteButton">Mute</button>

    <!--If the Change Music button is clicked, reveal more input-->
    <div id="inputVisible" style="display:none">
        <input type="text" id="URLId" placeholder="Insert URL Here">
        <button onclick="changeLink()">Swap Song</button>
        <br><button onclick="defaultMusic()" id="defaultButton">Switch to Default 2</button>
    </div>
</div>

A lot of this code, you probably don’t understand, but that’s ok. A lot of this code connects to the JavaScript part of this guide, which we’ll touch on later. I’ll note the most important attributes that should be reviewed. Each one has a comment above.

  1. The first line code actually loads the Youtube Player. Without this, there would be no video.
  2. There are Buttons that we defined to let the user change the music and mute it if need be.
  3. If the Change music button is clicked, inputs to change the music will be revealed.

So in a nutshell, this code allows us to load the youtube video & allow the user to mute and customize the music. Now we’ll go into actually how all of this works through a bit of JavaScript coding.

JavaScript Input

Before we setup the youtube player, we first need to setup the buttons which allow the user to interact the video.

The first and most important button is the Change Music button. This button allows the users to change the music to nearly any video on Youtube.

// Input Bar Revealer
let inputBar = true;
function input() {
    const inputVisible = document.getElementById("inputVisible");

    //Shows the input bar if previously unavaliable
    if (inputBar) {
        inputVisible.style.display = "block";
        document.getElementById("swapInput").innerHTML = "Hide Input"
    } 
    //Hides it if previously avaliable
    else {
        inputVisible.style.display = "none";
        document.getElementById("swapInput").innerHTML = "Show Input"
    }
    inputBar = !inputBar;
}

This first part, as per the definition, of the comment, reveals the input bar. This input bar is what allows you to change the music. What the code is doing is if the input bar isn’t there, pressing the button shows it, while if it’s already there, pressing the button hides it. The way it does this is by changing the display of inputVisible. When it’s shown, inputVisible is a block, else it’s defined as “none,” which just means it’s invisible.

The next part of codeactually defines how to change the music.

// Code for video swapper
let player;
function changeLink() {
    const inputText = document.getElementById("URLId").value;
    if (inputText.length >= 11) {
        const videoId = inputText.substring(inputText.length - 11);
        player.loadVideoById(videoId);
    }
}

When the Swap Song button is pressed (can be found in the html section), the function changeLink will activate. This function takes the URL, manipulates it, and then feeds it into the Youtube API. Just like that, the music is changed.

The last button, the mute button, is formatted as follows:

// Mute Button
function mute() {
  if (player.isMuted()) {
      player.unMute();
      document.getElementById("muteButton").innerHTML = "Mute"
  } else {
      player.mute();
      document.getElementById("muteButton").innerHTML = "Unmute"
  }
  isMuted = !isMuted;
}

Basically, if the mute button is pressed, two things can happen. If the video has already been muted, then pressing the button unmutes the video. However, if it hasn’t been muted yet, pressing the buttion mutes the video. You’ll see just like the code above, it’s manipulating the player variable, which is part of the Youtube API, which now we’ll finally get into.

Youtube API

The first step in using the Youtube API is loading it onto the device.

// Load the YouTube IFrame API asynchronously
const tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
const firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

This code is a bit complex (as much of the code in Youtube API documentation), but put simply, this code makes sure that the Youtube IFrame API is loaded onto the pag before any other script, which makes sure everything connects to the Youtube API correctly. While this loads the Youtube API onto the web, we still need to make use of it.

// This function creates an <iframe> (and YouTube player) after the API code downloads.
function onYouTubeIframeAPIReady() {
  
  //Properties for Youtube Player
  player = new YT.Player('player', {
      height: '0',
      width: '0',
      videoId: "xZhrZMervZU",
      playerVars: {
          'autoplay': 1, //Automatically Plays Video
          'loop': 1 //Loops Audio
      },
  });
}

This final and last bit of code defines the properties of the Youtube API on our device. You can see how we used it to be purely an auditorial experience. The height and width of IFrame is 0 & 0, making it so nothing can be seen but only music can be heard. The next property defines the default video to play, so the default music choice in our case.

The last two properties, are autoplay and loop. This makes sures the video plays automatically when loaded and when the video finishes, it just loops itself.

Ending Note

The Youtube API is a very, very powerful tool in which web developers, such as you and me, can host Youtube Videos on our websites. And with a little bit of ingenuity, you can use it for many purposes, such as our purpose of creating customizable music for our game. If there is anything to take out of this guide, it wouldn’t necessarily be the Youtube API, but the power of APIs in general and how they can be used to signficantly improve the experience of one’s website. They truly allow for creative thinking to flourish.