Video autoplay angular

Back-end
9 minute read

Building an Angular Video Player with Videogular

Video accounts for more than three quarters of all bandwidth used today. Thats why developers need a solid, extensible, and advanced media framework that doesnt come with a steep learning curve. In this tutorial, Toptal Freelance Software Engineer Raul Jimenez will introduce you to one such framework Videogular. If you need to harness the power of Angular for HTML5 video, look no further.

Author
Author
Raul Jimenez Herrando
A JS developer since 2001, Raul is the creator of Videogular and an expert in Angular, high-performance web apps, and video streaming.
SHARE
SHARE
The Videogular project is supported by Toptal Open Source Grants. Toptal Open Source Grants supports members of the Toptal network pursuing Open Source projects.

As one of the first Open Source Grants recipients, Raul Jimenez Herrando is adding new features, fixing bugs, and writing documentation for the Videogular project. To learn more about Toptal Open Source Grants, email .

According to online traffic statistics, video is taking over control of the web. The good old TV is dying and companies are moving fast to dominate a market that will represent the 80% of online traffic by 2019 .

Many media providers and products rely on HTML5 video support:

  • Youtube: HTML5 video and social sharing platform
  • Netflix: HTML5 video content provider
  • JWPlayer: HTML5 video service and streaming provider
  • Brightcove: HTML5 video service and streaming provider
  • Kaltura: HTML5 video service and streaming provider
  • Video.js: HTML5 video player
  • Flowplayer: HTML5 video player and streaming provider

The developer community needs a solid, extensible, and advanced media framework [not just an HTML5 video player] to face the new challenges that lay ahead. In this article, I want to introduce one such framework: Videogular.

What Is Videogular?

As the name suggests, Videogular is a media framework written in Angular 2+. With Videogular, you can play HTML5 video, audio, or any other content that you want. There is an implementation for Angular 1.X [a.k.a AngularJS], but in this article we will talk only about the current Angular 2+ version.

So, the next question that probably is crossing your mind is: Why use Angular for video?

Well, there are a number of good reasons for choosing a specific framework to create a video library.

  • Ease of contribution: Because Videogular is based on Angular, a popular framework with a very active community, its very easy for other people to start contributing by creating plugins or fixing bugs.
  • Web Components: No need to write JavaScript to create and style your own player. You can write HTML and CSS code.
  • TypeScript: Angular is a typed framework, as well as all the libraries around it. Having a strongly typed ecosystem allows us to detect bugs and architecture problems before its too late.
  • Speed: All the latest popular frameworks are blazing fast, including Angular.

Additionally, we have some other cool features like RxJS, AOT [ahead-of-time compilation], the Angular CLI, and more.

How Does Videogular Work?

I like to say that Videogular is more of a media framework than just an HTML5 video player. The most relevant feature and difference between other video players is that you write tags to set up your player instead of JavaScript.

This is how most video players work right now:

And this is what Videogular implementation looks like:

The good thing about Videogular is that, with just a quick look to the HTML code, you know how this player works, which controls are available, and how to modify it to remove, for example, the tracks and the track selector.

But this is not the only advantage we can benefit from when building an Angular video player. Think of big development teams where HTML/CSS designers and JavaScript developers work together on the same code base. Because were using custom elements, designers can start working by applying styles and animations without the need to learn a new library or even JavaScript/TypeScript.

Also, Videogular provides much more powerful capabilities than just writing a plain Angular video player, like automatic synchronization between several media files, or the ability to play not only video/audio, but just about any content that has a beginning and an end.

To see how easy is to create a rich, interactive app with Videogular, were going to create a video playlist with synchronized metadata.

How to Install Videogular

In this example, we will have a list of videos and a related excerpt from Wikipedia, just in case the user needs to have more information about the video.

All the code is available on our Videogular Showroom GitHub repo and its published as a GitHub page.

Videogular installation should be a straighforward affair for any skilled Angular developer. On the other hand, if youre just getting started in Angular, you should check out this quick guide to making your first Angular app.

If you have not installed Node.js yet, go to the Node.js official website and install it. This is the only server we need to develop with Angular, and we need it to install dependencies via NPM. You just need to be sure to install Node.js 6.9.0 or higher and NPM 3.0.0 or higher.

The first thing we need to do is to install the Angular CLI. The Angular CLI is a must-have tool for any Angular developer, since it provides easy scaffolding, testing, development servers, and productions builds. Even more importantly, it follows a convention that any other Angular developer can understand.

Install the Angular CLI globally via NPM:

npm install -g @angular/cli

And lets create our first project with support for SASS:

ng new smart-video-playlist --style=scss

This should create a sample project for you. If you want to start developing and watching the results at the same time, you can run npm run start and open [//localhost:4200][//localhost:4200]. The Angular CLI will run a Node.js development server with live reloading and all the cool features that we as developers love.

Now you can install the videogular2 library and core-js typings:

npm install videogular2 --save npm install @types/core-js --save-dev

Creating an Angular video player

If you want to, you can use the official Videogular font to set icons on your buttons and controls. To do that you need to add CSS to your .angular-cli.json file available on the root of your project.

{ ... "apps": [ { ... "styles": [ "../node_modules/videogular2/fonts/videogular.css", "styles.scss" ], ... } ], ... }

If you want to set your own font and styles, you can set your custom CSS here or inside styles.scss.

To start using Videogular in your project, you have to add the Videogular module to your application module.

Open src/app/app.module.ts and remove the FormsModule and the HttpModule; we will not need them for this demo. This is how your app.module.ts file should like:

import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { VgCoreModule } from 'videogular2/core'; import { VgControlsModule } from 'videogular2/controls'; @NgModule[{ declarations: [ AppComponent ], imports: [ BrowserModule, VgCoreModule, VgControlsModule ], providers: [], bootstrap: [ AppComponent ] }] export class AppModule { }

With everything set up, we just need to write our HTML code!

Now you can run the server and enjoy your first video app powered by Angular and Videogular.

npm run start

Building a Media Playlist in Angular

To list our videos, we will create a simple array with all the options. Just keep in mind that you can load this list via a REST service with Angulars HttpModule, but for the sake of simplicity, we will do this hard-coded in this demo.

Open app.component.ts and add this array of videos and its interface:

import { Component } from '@angular/core'; export interface IMedia { title: string; src: string; type: string; } @Component[{ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [ './app.component.scss' ] }] export class AppComponent { playlist: Array = [ { title: 'Pale Blue Dot', src: '//static.videogular.com/assets/videos/videogular.mp4', type: 'video/mp4' }, { title: 'Big Buck Bunny', src: '//static.videogular.com/assets/videos/big_buck_bunny_720p_h264.mov', type: 'video/mp4' }, { title: 'Elephants Dream', src: '//static.videogular.com/assets/videos/elephants-dream.mp4', type: 'video/mp4' } ]; }

Now were ready to add the playlist below our player in the HTML file:

  • {{ item.title }}

Lets add some styles for the selected class and the hover effect:

ul { list-style-type: none; margin: 0; padding: 0; font-family: sans-serif; li { padding: 10px; cursor: pointer; &.selected { background-color: #dddddd; } &:hover { background-color: #cce6ee; } } }

The method onClickPlaylistItem will set the media to play on our Videogular player. Lets go now to app.component.ts to add the method:

// ... export class AppComponent { // ... currentIndex = 0; currentItem: IMedia = this.playlist[ this.currentIndex ]; onClickPlaylistItem[item: IMedia] { this.currentIndex = index; this.currentItem = item; } }

The property currentIndex will be used later to identify the current item and its position in the playlist. This is important to do infinite loop playlists and update the currentIndex when the user clicks on an item of the playlist.

Finally, we only have to modify the video element to set the source from the currentItem property handled by the playlist. We will create for this a simple binding to the src property of the HTML5 video element:

Now we can test our playlist and see how it works. The first video is loaded at the beginning and we can change between videos, so everythings fine! But we can make some tweaks and improve the experience by switching automatically between videos when a video is completed, and adding better overall management of the player state.

To do this we will need the Videogular API, a global service available on every Videogular instance to handle the state and listen for events.

Using VgAPI to handle states

Our media playlist is right now 100% functional, but we can improve the user experience by autoplaying videos when a new item is selected or when a video is completed.

Videogular exposes an API to control and listen for changes for each VgMedia instance inside the VgPlayer component. Actually, all Videogular modules are based in this public API, so you can create your own modules for your customers or contribute to the community by releasing them as open source.

To use the Videogular API, you just need to listen for the onPlayerReady event fired by the VgPlayer component:

// ...

When the player is initialized, you can save the API and start listening for the events dispatched by the video tag:

export class AppComponent { // ... onPlayerReady[api: VgAPI] { this.api = api; } }

The Videogular API is based on RxJS, so you can subscribe to Observables and react in consequence. To autoplay the videos, we need to listen for the loadedmetadata event.

Lets add a new Subscription to play the video when the metadata is loaded:

export class AppComponent { // ... onPlayerReady[api: VgAPI] { this.api = api; this.api.getDefaultMedia[].subscriptions.loadedMetadata.subscribe[ this.playVideo.bind[this] ]; } playVideo[] { this.api.play[]; } // ... }

That was easy; we simply play the video via the VgAPI when the loadedMetadata observable is fired.

Do you remember the currentIndex property? Now is the moment to use it so we can move to the next video when the current video is completed:

// ... export class AppComponent { // ... onPlayerReady[api: VgAPI] { this.api = api; this.api.getDefaultMedia[].subscriptions.loadedMetadata.subscribe[ this.playVideo.bind[this] ]; this.api.getDefaultMedia[].subscriptions.ended.subscribe[ this.nextVideo.bind[this] ]; } nextVideo[] { this.currentIndex++; if [this.currentIndex === this.playlist.length] { this.currentIndex = 0; } this.currentItem = this.playlist[ this.currentIndex ]; } // ... }

With this method, we can handle when the ended event is fired by the video tag and then move to the next video. We also added a small control to do an infinite loop when we reach the end of the playlist by setting currentIndex = 0; so we can move back to the first item. Finally we set the currentItem that will update our Angular bindings in the UI.

As you can see, were not playing the video here; thats because we handle that with the loadedMetadata observable. When we update the currentItem inside nextVideo[], a new video is loaded and that triggers the loadedMetadata observable.

This makes our code easier to read and harder to break! Observables are awesome right?

Whats next?

From here, we could add some HTML5 video controls to remove autoplay or the infinite loop, inject advertisements, or synchronize information.

In this demo, we just scratched the surface of whats possible to do with Videogular. The API is capable of managing several media files at the same time, we have modules for streaming and advertisement, and you can even create a media player to play animations, routes in a map, and much more.

Videogular is released under an MIT license and is an open-source project available on GitHub. Everybody is welcome to create a pull request, submit an issue, write documentation, and contribute to the community.

Understanding the basics

Who created AngularJS?

Angular was created and is currently maintained by Google, though as an Open Source framework, its community is supporting it a lot with external contributions, and some of these has been added to the core, like Angular Universal or the Angular CLI.

What is an HTML5 video?

HTML5 video is a native browser API to play video and audio files directly in the browser without the need for plugins like Flash or Silverlight. Video on the web has been evolved rapidly and right now is capable of doing anything that you can do with plugins.

What is Videogular?

Videogular is a powerful media framework powered by Angular. It's particularly useful for the creation of HTML5 website video players.

What is AngularJS/Angular 2+?

Angular is a JavaScript framework developed by Google. The community usually talks about AngularJS when they are referring to the Angular v1.X version, and just Angular when they talk about Angular v2.X and above.

Tags

AngularAngularJSHTML5HTML5VideoVideogular

Freelancer? Find your next job.

Remote Freelance Jobs
View full profile

Raul Jimenez Herrando

Developer

About the author

Raul is a front-end architect and technical consultant with over 15 years of experience. He's an expert with AngularJS, JavaScript, high-performance web applications, and video streaming. While he's not working on his open source project Videogular, you can find him practicing with new frameworks like React, Angular 2, and Polymer to stay always up-to-date.

Hire Raul

Comments

Sébastien Tromp
Hey Raul, I've been using videogular for some time now, and it's a really neat library. Keep up the good work!
Raúl Jiménez
Thanks man! I'll do my best!
Shweta Sindhu
hi not able to do autohide controls and scrub bar how to do.i have also added autohide property still not able to do.
machau kumar
Hey Raul, I am trying to use the code to play a list of videos as you guided. It is playing only audio,but not rendering the video. Please guide
oliver smith
//www.office-setup-install.us
test onebyte
Hi, can we play custom videos as ads ? with same skip ad functionality.
Muvva Saisudhakar
my videos Working fine.You are Awesome...
Developer Team
HI ,Raul We are using videogular player, we have some problem in our website , that video is not loading faster [suppose 10 min video is taking 10 sec to load and play]. Our video is stored in google cloud bucket. please suggest some solution to load video faster and play... please check below link: //therightdoctors.com/cardiac-prevent-2015/in-conversation/dr-h-K-chopra-with-dr-m-k-das-dr-shiv-Kumar-and-dr-amal-banerjee
vishnu vardhan
HI, Can anyone please explain how to tilt the video to 90/180/270/360 degrees using videogular
arpit arora
HI Raul m using vg-player and i am new in angular i want to hit some api after 10 min completion of video so please tell me how to do it please reply asap Thanks in advance
Marcio Motta
Hello everyone, everything good? Does anyone know if it is possible to run wmv files? Thank you!
Dnyaneshwar Suryawanshi
Helllo , I have create videoplayer using videogular. Below is my code As you seen i have applied [muted]="true" then my video is muted but when i tried to unmute based on mouse click it's not going to reflect the change. Kindly please help.
jacob
Hi Raul Thank you for the wonderful software. I am experiencing an issue displaying video on iphone although works on every other device. Is this a known issue ?
Rishabh
thanks for sharing this it save so much of time and this post helps a lot
Please enable JavaScript to view the comments powered by Disqus.comments powered by Disqus

World-class articles, delivered weekly.

Get great content

Subscription implies consent to our privacy policy

Thank you!
Check out your inbox to confirm your invite.

Trending Articles

EngineeringIcon ChevronTeams and Processes

8 Automated Testing Best Practices for a Positive Testing Experience

EngineeringIcon ChevronWeb Front-end

Creating React Apps With Redux Toolkit and RTK Query

EngineeringIcon ChevronData Science and Databases

Graph Data Science With Python/NetworkX

EngineeringIcon ChevronBack-end

Using Express.js Routes for Promise-based Error Handling

See our related talent

AngularJSHTML5

Freelancer? Find your next job.

Remote Freelance Jobs

Hire the author

View full profile

Raul Jimenez Herrando

Developer

Read Next

EngineeringIcon ChevronData Science and Databases

How I Made Porn 20x More Efficient with Python Video Streaming

Video liên quan

Chủ Đề