We have already explored how to incorporate audio and video files into our HTML, but we can also control the playback and various properties of these media assets using JavaScript.
A little additional logic and reading the paused property from the audio HTML element allows us to toggle playing and pausing the audio with a single button. Note that we need to use the vanilla JavaScript document.querySelector() method to access the HTML media element in order to have access to the paused property.
Dealing with a YouTube video embedded in an iFrame is a little bit different and involves having more of an understanding of the YouTube API. The example below loads a YouTube video using JavaScript, and when the user hits play it will begin a 6 second timer upon which point it will automatically be stopped.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
width: '100%',
videoId: 'Q_GFgmvF_eE',
playerVars: {
'playsinline': 1,
'controls': 0
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
done = false;
}