视频流,角度:IOS 上的 HLS

分享于2022年07月17日 angular http-live-streaming ios 问答
【问题标题】:视频流,角度:IOS 上的 HLS(Video Streaming, Angular: HLS on IOS)
【发布时间】:2022-01-24 06:17:23
【问题描述】:

我正在尝试使用 HLS.js 实现一项功能以在 IOS 上实现视频流。我检查了该库不支持 HLS 的文档,但可以回退到本机 <video> 标签来播放 m3u8 视频。我不知道这应该如何工作。非常感谢任何帮助。

在netlify上部署的应用: https://angular-hls-player.netlify.app/

这是我迄今为止在 Angular 中所做的:

import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';
import Hls from 'hls.js';

@Component({
  selector: 'app-video-player',
  templateUrl: './video-player.component.html',
  styleUrls: ['./video-player.component.scss']
})
export class VideoPlayerComponent implements AfterViewInit {
  @ViewChild('videoPlayer') videoElementRef!: ElementRef;
  @ViewChild('play') buttonElementRef!: ElementRef;

  videoElement!: HTMLVideoElement;
  buttonElement!: HTMLButtonElement;

  constructor() { }

  ngAfterViewInit(): void {
    if (Hls.isSupported()) {
      console.log("Video streaming supported by HLSjs")
      this.videoElement = this.videoElementRef?.nativeElement;

      var hls = new Hls();
      hls.loadSource('https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8');
      hls.attachMedia(this.videoElement);
      hls.on(Hls.Events.MANIFEST_PARSED, () => {
        this.videoElement.play();
      });
    }
    // the video is supposed to be playing on IOS devices
    else if (this.videoElement.canPlayType('application/vnd.apple.mpegurl')) {
      alert("The video is on the iPhone or iPad environment!")
      this.videoElement.src = 'https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8';
      this.videoElement.addEventListener('canplay', () => {
        alert("Fire the canplay event");
        this.startPlaying();
      })
    }
  }

  startPlaying() {
    this.videoElement.play();
  }
}

html部分:

HLS JS Player


【解决方案1】:

我发现 videoElement 需要分配 ElementRef nativeElement 才能访问DOM 元素。因此:

else if (this.videoElement.canPlayType('application/vnd.apple.mpegurl')) {
   this.videoElement = this.videoElementRef?.nativeElement;
   this.videoElement.src = 'https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8';
}