Angular 4项目中集成JW Player的方法咨询
Hey there! Let's walk through how to get JW Player up and running smoothly in your Angular 4 project—since you've already added the jwplayer.js path in .angular-cli.json, we're halfway there. Here's a step-by-step breakdown tailored to your setup:
.angular-cli.json Setup First, double-check that you've added the JW Player script (and optional skin CSS) correctly in your configuration file. It should look something like this:
"apps": [ { // ... other app config "styles": [ // Add JW Player skin CSS if you're using one "../node_modules/jwplayer/skins/Glow/glow.css" ], "scripts": [ // Path to your jwplayer.js file "../node_modules/jwplayer/jwplayer.js" ] } ]
Note: Adjust the paths to match where you've stored the JW Player files in your project.
Since Angular uses TypeScript, we need to let it know that the global jwplayer variable exists. Create or update a src/typings.d.ts file with this line:
declare var jwplayer: any;
This prevents TypeScript from throwing "cannot find name 'jwplayer'" errors.
Create a dedicated component to handle the JW Player instance—this keeps your code clean and reusable.
- Generate the component (or create the files manually):
ng generate component video-player
- Update
video-player.component.tswith this code:
import { Component, OnInit, ElementRef, ViewChild, OnDestroy } from '@angular/core'; @Component({ selector: 'app-video-player', template: `<div #playerContainer class="jw-player-container"></div>` }) export class VideoPlayerComponent implements OnInit, OnDestroy { @ViewChild('playerContainer') playerContainer: ElementRef; private player: any; ngOnInit() { // Initialize JW Player this.player = jwplayer(this.playerContainer.nativeElement); this.player.setup({ file: 'https://example.com/your-video-file.mp4', // Replace with your video URL width: '100%', height: 480, autostart: false, controls: true, playlist: false }); } ngOnDestroy() { // Clean up the player to avoid memory leaks if (this.player) { this.player.remove(); } } }
Add the player component to any template where you want to display the video. For example, in app.component.html:
<div class="video-wrapper"> <app-video-player></app-video-player> </div>
- Skin Styling: If you're using a JW Player skin, make sure its CSS is included in the
stylesarray of.angular-cli.json(as shown in Step 1) to ensure proper rendering. - Video Sources: You can use direct video URLs, HLS streams, or playlists—just update the
fileorplaylistproperty in the setup config. - Player Controls: Customize the player behavior by adjusting the setup options (e.g.,
autostart,controls,volume, etc.) to match your needs.
内容的提问来源于stack exchange,提问作者Nitin yadav

