Angular项目中用Plyr+hlsjs串行播放多个m3u8流的方法
实现单个Plyr串行播放多个m3u8源的方案
1. 基础配置确认
确保项目已正确集成依赖:
- 安装依赖:
npm install plyr ngx-plyr hls.js - 在Angular模块中导入
NgxPlyrModule - 组件中引入
Plyr和Hls类
2. 模板与组件核心实现
模板部分
<ngx-plyr #plyrPlayer [options]="playerOpts" (ended)="onCurrentVideoEnd()"></ngx-plyr>
核心是通过ended事件监听当前视频播放完成,触发切换逻辑。
组件逻辑
import { Component, ViewChild } from '@angular/core'; import { PlyrComponent } from 'ngx-plyr'; import Plyr from 'plyr'; import Hls from 'hls.js'; @Component({ selector: 'app-stream-player', templateUrl: './stream-player.component.html', styleUrls: ['./stream-player.component.css'] }) export class StreamPlayerComponent { @ViewChild('plyrPlayer') plyrPlayer!: PlyrComponent; playerOpts: Plyr.Options = { controls: ['play-large', 'play', 'progress', 'current-time', 'mute', 'volume', 'fullscreen'], autoplay: false }; // 定义需串行播放的m3u8源列表 streamSources = [ { src: 'https://your-domain.com/first-stream.m3u8', type: 'application/x-mpegURL' }, { src: 'https://your-domain.com/second-stream.m3u8', type: 'application/x-mpegURL' } ]; currentPlayIndex = 0; ngAfterViewInit() { // 初始化播放第一个源 this.loadStreamSource(this.currentPlayIndex); } private loadStreamSource(index: number) { const targetSource = this.streamSources[index]; if (!targetSource) return; // 销毁旧的Hls实例,避免内存泄漏或播放冲突 if ((this.plyrPlayer.player as any).hlsInstance) { (this.plyrPlayer.player as any).hlsInstance.destroy(); } // 更新Plyr的媒体源 this.plyrPlayer.player.source = { type: 'video', sources: [targetSource] }; // 初始化Hls.js处理m3u8流 if (Hls.isSupported()) { const hls = new Hls(); hls.loadSource(targetSource.src); hls.attachMedia(this.plyrPlayer.player.media); // 保存Hls实例到player对象,方便后续销毁 (this.plyrPlayer.player as any).hlsInstance = hls; // 可选:添加错误监听,处理加载失败场景 hls.on(Hls.Events.ERROR, (_, data) => { if (data.fatal) { console.error('流加载失败,自动切换下一个'); this.onCurrentVideoEnd(); } }); } else if (this.plyrPlayer.player.media.canPlayType('application/x-mpegURL')) { // 兼容原生支持HLS的浏览器(如Safari) this.plyrPlayer.player.media.src = targetSource.src; } // 加载并播放当前源 this.plyrPlayer.player.load(); this.plyrPlayer.player.play(); } onCurrentVideoEnd() { // 切换到下一个源 this.currentPlayIndex++; if (this.currentPlayIndex < this.streamSources.length) { this.loadStreamSource(this.currentPlayIndex); } else { // 所有源播放完毕,可选择重置循环或停止 this.currentPlayIndex = 0; // this.loadStreamSource(this.currentPlayIndex); // 开启则循环播放 } } }
3. 关键注意事项
- 销毁旧Hls实例:每次切换源必须销毁之前的Hls实例,否则会导致播放异常或内存泄漏。
- 动态更新源:不能依赖Plyr默认的多源列表自动串行播放,因为Hls.js需要重新绑定新的媒体资源。
- 兼容性处理:区分Hls.js支持的浏览器和原生支持HLS的浏览器(如Safari),分别处理播放逻辑。
- 错误兜底:添加Hls错误监听,在流加载失败时自动切换下一个源,提升播放稳定性。
内容的提问来源于stack exchange,提问作者or123456
相关产品推荐
相关产品推荐

