Guide on integrating the plyr npm module for creating a video player in Angular2

Looking to implement the Plyr npm package in an Angular 6 application to create a versatile video player capable of streaming m3u8 and Youtube videos. The demos on their npm page are written in plain JavaScript, so I need guidance on how to integrate it into an Angular 6 app.

Specifically, I'm interested in learning how to utilize Hls with this package.

Would appreciate help understanding these two examples: https://codepen.io/pen?template=oyLKQb#enter code here

https://codepen.io/pen?template=GGqbbJenter code here

Answer №1

There are two options available for integrating a video player into your Angular project. The first option involves using the ngx-plyr npm package, while the second option requires directly integrating the plyr js library.

Option #1: Utilize the angular npm package ngx-plyr

To implement option one, you can install the ngx-plyr npm package by running:

npm i plyr ngx-plyr

Then, refer to the ngx-plyr github usage instructions or explore a simple stackblitz demo.

Option #2: Implement the plyr js lib

If you prefer to use the plyr js library directly, follow these steps:

  1. Install plyr via yarn or npm by running npm i plyr
  2. Add the plyr CSS and JS files to your angular.json configuration:

    ...
    "styles": [
        "src/styles.scss",
        "node_modules/plyr/dist/plyr.css"
    ],
    "scripts": [
        "node_modules/plyr/dist/plyr.js"
    ]
    ...

  3. Incorporate the video tag into your HTML template file, ensuring to assign an ID to link the template and component as shown below:

    <div class="container">
    <video id='plyrID' controls crossorigin playsinline poster="https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.jpg">
        <source src="https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-576p.mp4" type="video/mp4" size="576">
        <source src="https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-720p.mp4" type="video/mp4" size="720">
        <source src="https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-1080p.mp4" type="video/mp4" size="1080">
    
        <!-- Caption files -->
        <track kind="captions" label="English" srclang="en" src="https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.en.vtt"
               default>
        <track kind="captions" label="Français" srclang="fr" src="https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.fr.vtt">
        <!-- Fallback for browsers that don't support the <video> element -->
        <a href="https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-576p.mp4" download>Download</a>
    </video>
    

  4. Create a new instance of Plyr in your component like so:

    import { Component, OnInit} from '@angular/core';
    import * as Plyr from 'plyr';
    
    @Component({
      selector: 'test',
      templateUrl: './test.html',
    })
    export class TestComponent {
    export class TestComponent implements OnInit {
    
      public player;        
    
      ngOnInit() {
          this.player = new Plyr('#plyrID', { captions: { active: true } });
      }
    
    }
    

You can view a stackblitz demo that demonstrates direct usage of the plyr js library with some adjustments made due to stackblitz constraints.

Answer №2

Implementing the Plyr js player in an Angular version 16 project

Step 1 - Begin by installing the plyr package using the command line

npm i plyr

Step 2 - Include the plyr css and js files in your angular.json configuration under styles and scripts respectively

...
"styles": [
    "src/styles.scss",
    "node_modules/plyr/dist/plyr.css"
    ],
"scripts": [
    "node_modules/plyr/dist/plyr.js"
]
...

Step 3 - Declare the Plyr package in your component's Typescript file.

import { Component } from '@angular/core';

declare var Plyr: any;

@Component({
    ....
})

export class AppComponent {
player: any;   

 ngAfterViewInit() {
    this.player = new Plyr('#video_player', {
        youtube: {
            rel: 0,
            showinfo: 0,
            iv_load_policy: 3,
            modestbranding: 1,
            customControls: true,
            noCookie: true
        }
    });

    this.player.source = {
        type: 'video',
        sources: [
            {
                src: 'https://www.youtube.com/watch?v=slAbFqZonT0',
                provider: 'youtube'
            },
        ]
    };

    this.player.on('ended', () => {
        this.player.stop()
    });
}

Step 4 - Insert the Html player content into the html component file

<div class="container">
    <video id="video_player"></video>
</div>

Answer №3

Installing plyr and ngx-plyr packages:

npm i plyr ngx-plyr

Setting up Plyr player for YouTube video:

<div id="plyrID" data-plyr-provider="youtube" data-plyr-embed-id="IQFc5u63cCk"></div>

Importing Plyr module:

import * as Plyr from 'plyr';

Initializing Plyr player in ngOnInit method:

ngOnInit( ) {

  this.player = new Plyr('#plyrID', { 
    debug: true,
    volume: 0,
    autoplay: true,
    muted:false,
    loop: { active: true },

  });

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to invoke a function in Typescript while retrieving data?

Is it possible to run a query in my main.ts file with another ts file and then pull the result of the query into another file? If so, how can this be achieved? Here is an example from my main.ts file: async function getAllTips() { const tips: any = []; ...

"Trouble arises with the implementation of the routerLink directive

I have been developing an Angular2 application that involves routing with the component router. Currently, I am using angular-2.0.0-beta.3. When trying to use the routerlink directive in a child component, my template looks like this: <a [routerLink] ...

Incorporate FontAwesome global components into your Vue project using TypeScript

Hey there, I'm a TypeScript newbie and looking to incorporate FontAwesome icons into my Vue 3 App. Here's the setup: Here is my main.ts : import Vue, { createApp } from 'vue'; import './registerServiceWorker'; import { librar ...

What is the best way to implement type discrimination in TypeScript?

When using TypeScript with two interfaces combined as a union type, why doesn't it distinguish which type members can be declared? interface IFish { swim: () => void; } interface ICat { meow: () => void; } type Pet = IFish | ICat; const p ...

Encountering an issue when attempting to establish a connection to Redis using a cache manager within a Nest

Incorporating the NestJS framework into my project and utilizing Cash Manager to connect with Redis cache. Successfully connected with Redis, however encountering an error when attempting to use methods like set/get which shows 'set is not a function& ...

Combining Bootstrap admin template with SCSS styling in Angular 2

Currently seeking a complimentary bootstrap template featuring scss style to incorporate into my angular project. Is there anyone who can guide me on the correct procedure for this task? I stumbled upon a potential template on github but I am having diffic ...

Typescript's intriguing concept of objects containing arrays inside other objects

I have a structure similar to this and I am trying to create definitions for types/interfaces, but I am facing issues in making it work correctly. layoutsSet: { 1: { "lg": [ { i: "1", x: 0, ...

Executing NestJS code after applying a pipe but before reaching the method handler

Is it possible to insert additional code after all the pipes have transformed but before the method handler is called? https://i.sstatic.net/IjQvv.png ...

Guide on setting up redux store from server component using next.js and app router

I'm currently working with Next.js 13, React, and Redux to handle state management. My main objective is to fetch initial data on the server side and present it on the client side. Although I assumed this would be a typical approach with Redux and Ne ...

Access an array to filter by specific key-value pairs

How can I efficiently filter an array using key and value pairs from within nested arrays? I am in need of a method to filter the elements of an array based on specific key-value pairs nested within another array. The key will always contain boolean value ...

Move the creation of the HTML string to an HTML template file within ngx bootstrap popover

I have incorporated ngx bootstrap in my project through this link To display dynamic HTML content in the popover body, I am using a combination of ngx-bootstrap directives and Angular template syntax as shown below: <span *ngFor="let item of items;"&g ...

Creating a Jira-inspired table layout in Angular by embedding components in a structured format

I'm attempting to recreate the functionality of Jira where I can create a "gadget" that can be added to a board, resized, moved, and deleted. (For those unfamiliar with why this might be useful, think of gadgets like the "Gantt" gadget. You can add a ...

conditionally trigger one observable in rxjs before the other

I am in need of assistance or guidance regarding a challenge I am facing with rxjs that I cannot seem to resolve. In essence, my goal is to trigger an observable and complete it before the original one is triggered. Scenario: I am currently working on a ...

What is the best way to generate an object in TypeScript with a variety of fields as well as specific fields and methods?

In JavaScript, I can achieve this using the following code: var obj = { get(k) { return this[k] || ''; }, set(k, v) { this[k] = v; return this; } }; obj.set('a', 'A'); obj.get('a'); // returns &ap ...

Develop a query builder in TypeORM where the source table (FROM) is a join table

I am currently working on translating this SQL query into TypeORM using the QueryBuilder: SELECT user_places.user_id, place.mpath FROM public.user_root_places_place user_places INNER JOIN public.place place ON place.id = user_places.place_id The ...

Increase the timestamp in Typescript by one hour

Is there a way to extend a timestamp by 1 hour? For instance, 1574620200000 (Including Microseconds) This is my date in timestamp format. How can I add a value to the timestamp to increase the time by an additional hour? ...

What is the method for retrieving service values in Angular2?

I've been following the Angular2 tutorial steps at this link: https://angular.io/docs/ts/latest/tutorial/toh-pt4.html There's a particular syntax used to return service promise information back to the component, as shown here: getHeroes() { t ...

How can we direct the user to another tab in Angular Mat Tab using a child component?

Within my Angular page, I have implemented 4 tabs using mat-tab. Each tab contains a child component that encapsulates smaller components to cater to the specific functionality of that tab. Now, I am faced with the challenge of navigating the user from a ...

Utilizing Angular to automatically extract keys from nested objects in a response

In my Angular application, I am facing a challenge with accessing nested responses from the server. The data structure contains multiple responses within one parent object, and I am struggling to dig deeper into it. Here is the code snippet I have so far: ...

Angular CRUD Form Data Conversion Update

After selecting the date 3/2/2021 in my Angular create CRUD form, it gets passed to MongoDB as 2021-03-02T00:00:00.000+00:00 and then displayed on the update CRUD form as 2021-03-02T00:00:00.000Z. How can I convert this to 'M/d/yyyy' format? (I ...