Design a Web Function Which Can Upload a Video in the Web Page in Angular 2

The Videogular projection is supported by Toptal Open Source Grants. Toptal Open Source Grants supports members of the Toptal network pursuing Open Source projects.

Equally 1 of the first Open up Source Grants recipients, Raul Jimenez Herrando is adding new features, fixing bugs, and writing documentation for the Videogular project. To learn more than nigh Toptal Open up Source Grants, email opensource@toptal.com.

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

Many media providers and products rely on HTML5 video back up:

  • 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 histrion
  • 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 confront the new challenges that lay alee. In this article, I want to introduce i such framework: Videogular.

What Is Videogular?

Every bit the proper noun suggests, Videogular is a media framework written in Angular 2+. With Videogular, yous can play HTML5 video, sound, or whatsoever other content that you want. At that place is an implementation for Angular 1.X (a.k.a AngularJS), but in this article we will talk just about the current Angular ii+ version.

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

Cover illustration: Building an Angular video player

Well, in that location 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, it's very easy for other people to start contributing by creating plugins or fixing bugs.
  • Web Components: No need to write JavaScript to create and manner your ain role player. You can write HTML and CSS code.
  • TypeScript: Angular is a typed framework, as well equally all the libraries around it. Having a strongly typed ecosystem allows us to detect bugs and architecture problems before it'due south too tardily.
  • Speed: All the latest pop frameworks are blazing fast, including Athwart.

Additionally, we accept some other absurd features similar RxJS, AOT (ahead-of-time compilation), the Angular CLI, and more than.

How Does Videogular Work?

I similar to say that Videogular is more of a media framework than only an HTML5 video role player. The well-nigh relevant feature and departure betwixt other video players is that you lot write tags to ready your player instead of JavaScript.

This is how most video players piece of work right at present:

          <video class="library" controls preload="auto" data-config="some-js-object-here">   <source src="video-url.mp4" type='video/mp4'> </video>   <script src="video-library.js"></script>                  

And this is what Videogular implementation looks like:

          <vg-player>    <vg-overlay-play></vg-overlay-play>    <vg-buffering></vg-buffering>      <vg-controls>        <vg-play-suspension></vg-play-pause>        <vg-fourth dimension-display vgProperty="current" vgFormat="mm:ss"></vg-fourth dimension-display>          <vg-scrub-bar>           <vg-scrub-bar-current-time></vg-scrub-bar-current-time>           <vg-scrub-bar-buffering-time></vg-scrub-bar-buffering-fourth dimension>        </vg-scrub-bar>          <vg-fourth dimension-brandish vgProperty="full" vgFormat="mm:ss"></vg-time-display>          <vg-rails-selector></vg-track-selector>        <vg-mute></vg-mute>        <vg-volume></vg-volume>          <vg-fullscreen></vg-fullscreen>    </vg-controls>      <video #myMedia [vgMedia]="myMedia" id="myVideo" preload="auto" crossorigin>        <source src="video-url.mp4" blazon='video/mp4'>        <track kind="subtitles" characterization="English language" src="avails/subs/pale-blueish-dot.vtt" srclang="en" default>        <track kind="subtitles" label="Español" src="assets/subs/pale-bluish-dot-es.vtt" srclang="es">    </video> </vg-player>                  

The good affair about Videogular is that, with just a quick wait to the HTML code, you know how this player works, which controls are available, and how to modify information technology to remove, for example, the tracks and the runway selector.

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

Besides, Videogular provides much more powerful capabilities than merely writing a obviously Angular video player, like automatic synchronization betwixt several media files, or the ability to play non only video/audio, but merely about any content that has a beginning and an end.

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

How to Install Videogular

In this instance, we volition have a list of videos and a related excerpt from Wikipedia, just in case the user needs to have more data near the video.

All the code is bachelor on our Videogular Showroom GitHub repo and it'due south published equally a GitHub page.

Videogular installation should be a straighforward matter for whatever skilled Angular developer. On the other hand, if yous're just getting started in Angular, you should check out this quick guide to making your first Athwart app.

If you accept not installed Node.js notwithstanding, go to the Node.js official website and install it. This is the only server we demand to develop with Angular, and we need it to install dependencies via NPM. You merely demand to be sure to install Node.js 6.9.0 or higher and NPM three.0.0 or higher.

The showtime affair nosotros demand to practise is to install the Athwart CLI. The Angular CLI is a must-accept tool for any Athwart developer, since it provides easy scaffolding, testing, evolution servers, and productions builds. Fifty-fifty more chiefly, it follows a convention that any other Athwart developer can understand.

Install the Angular CLI globally via NPM:

          npm install -thou @athwart/cli                  

And allow's create our showtime project with back up for SASS:

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

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

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

          npm install videogular2 --save npm install @types/cadre-js --relieve-dev                  

Creating an Athwart video actor

If you want to, you can utilize the official Videogular font to prepare icons on your buttons and controls. To practice that you lot need to add together 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 lot want to prepare your own font and styles, yous tin prepare your custom CSS here or inside styles.scss.

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

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

          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 form AppModule { }                  

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

          <vg-player>    <vg-controls>        <vg-play-intermission></vg-play-pause>        <vg-playback-button></vg-playback-push button>          <vg-time-display vgProperty="electric current" vgFormat="mm:ss"></vg-fourth dimension-display>          <vg-scrub-bar>            <vg-scrub-bar-electric current-time></vg-scrub-bar-current-time>            <vg-scrub-bar-buffering-time></vg-scrub-bar-buffering-time>        </vg-scrub-bar>          <vg-time-display vgProperty="total" vgFormat="mm:ss"></vg-time-display>          <vg-mute></vg-mute>        <vg-volume></vg-volume>          <vg-fullscreen></vg-fullscreen>    </vg-controls>      <video #media [vgMedia]="media" id="singleVideo" preload="auto" crossorigin>        <source src="http://static.videogular.com/avails/videos/videogular.mp4" type="video/mp4">    </video> </vg-player>                  

Now yous can run the server and relish your first video app powered by Angular and Videogular.

          npm run start                  

To list our videos, nosotros volition create a simple array with all the options. Just keep in mind that you can load this list via a REST service with Athwart'south HttpModule, simply for the sake of simplicity, we will practise this hard-coded in this demo.

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

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

Now we're fix to add together the playlist below our player in the HTML file:

          <ul>    <li *ngFor="let detail of playlist; permit $alphabetize = alphabetize"        (click)="onClickPlaylistItem(item, $index)"        [grade.selected]="item === currentItem">        {{ detail.title }}    </li> </ul>                  

Let's add some styles for the selected class and the hover result:

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

The method onClickPlaylistItem will set the media to play on our Videogular player. Let's become at present to app.component.ts to add the method:

          // ... export grade AppComponent {    // ...       currentIndex = 0;     currentItem: IMedia = this.playlist[ this.currentIndex ];       onClickPlaylistItem(particular: IMedia) {         this.currentIndex = alphabetize;         this.currentItem = item;     } }                  

The holding currentIndex will be used later to place 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 but have to modify the video element to gear up the source from the currentItem holding handled by the playlist. Nosotros volition create for this a simple binding to the src property of the HTML5 video element:

          <video #media       [vgMedia]="media"       [src]="currentItem.src"       id="singleVideo"       preload="auto"       crossorigin> </video>                  

Now nosotros tin test our playlist and see how it works. The kickoff video is loaded at the beginning and we can alter betwixt videos, so everything's fine! But we can make some tweaks and meliorate the experience past switching automatically between videos when a video is completed, and adding amend overall management of the player state.

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

Using VgAPI to handle states

Our media playlist is right now 100% functional, but we can ameliorate 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 mind for changes for each VgMedia instance inside the VgPlayer component. Really, all Videogular modules are based in this public API, so you can create your ain modules for your customers or contribute to the community by releasing them as open source.

To use the Videogular API, you only need to listen for the onPlayerReady upshot fired past the VgPlayer component:

          <vg-role player (onPlayerReady)="onPlayerReady($event)"> // ...                  

When the role player is initialized, you tin can save the API and kickoff listening for the events dispatched past 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 outcome.

Let's add a new Subscription to play the video when the metadata is loaded:

          consign course AppComponent {    // ...      onPlayerReady(api: VgAPI) {        this.api = api;        this.api.getDefaultMedia().subscriptions.loadedMetadata.subscribe(            this.playVideo.bind(this)        );    }      playVideo() {       this.api.play();    }      // ... }                  

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

Exercise you remember the currentIndex property? Now is the moment to apply it then nosotros tin can move to the next video when the electric 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.demark(this)        );    }      nextVideo() {        this.currentIndex++;          if (this.currentIndex === this.playlist.length) {            this.currentIndex = 0;        }          this.currentItem = this.playlist[ this.currentIndex ];    }      // ... }                  

With this method, we tin handle when the concluded result is fired by the video tag and and so move to the side by side video. We besides added a small control to practise an space loop when we reach the terminate of the playlist by setting currentIndex = 0; so we tin move back to the kickoff item. Finally we set the currentItem that will update our Angular bindings in the UI.

As y'all tin see, we're non playing the video here; that's because we handle that with the loadedMetadata observable. When nosotros 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 pause! Observables are awesome right?

What's next?

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

In this demo, we but scratched the surface of what'southward 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 role player to play animations, routes in a map, and much more.

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

baileyalinst.blogspot.com

Source: https://www.toptal.com/angular-js/angular-video-player-videogular

0 Response to "Design a Web Function Which Can Upload a Video in the Web Page in Angular 2"

Enviar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel