Chrome (Android) video autoplay inside Angular 2+ component

依然范特西╮ 提交于 2019-11-29 08:06:59

Answer and work-around to OP and to question in my own comment: Yes, appending a video tag as vanilla HTML to an already initialized Angular component works as expected (confirmed at least in Chrome & FF). Just happened to need this for my own project today. :)

So you can do something like this, or a pipe that returns the HTML for a given video URL (which is much better perf-wise, google "Angular Pipes").

<div *ngFor="let file of files" [innerHTML]="getVideoTag(file)"></div>

// component
  getVideoTag(file) {
    return this.domSanitizer.bypassSecurityTrustHtml(
      `<video width="1280" height="720" autoplay muted controls>
          <source src="${file.url}" type="video/mp4">No HTML5 supported.</source>
       </video>`
    );
  }

I was searching for this issue a lot and I put the muted attribute like this:

[muted]="true" rather than just muted

and now it works

<video [muted]="true" autoplay>
    <source src="path/to/video.mp4" type="video/mp4" />
</video>

Chrome has a policy to not let videos autoplay if the user has not first interacted with the page however if its a muted video chrome allows it. The problem here is that for some reason muted value goes as false when you just put muted in angular.

Similar issue with Angular 6 and Chrome 70.

In fact, the muted attribute in the HTML seems to be ignored by Chrome when the video is added by Angular. The resulting DOM element has a 'muted' property set to 'false'. Not sure if it is an Angular or a Chrome bug.

You need to set it manually to true to make the autoplay work.

I ended up with a directive :

@Directive({selector: '[my-autoplay]' })
export class AutoplayVideoDirective implements OnInit {

  constructor(public element: ElementRef) { }

  public ngOnInit(): void {
    let vid = this.element.nativeElement;
    vid.muted = true;
    vid.play();
  }
}

and the HTML :

<video loop muted autoplay my-autoplay>

I needed to use both onloadedmetadata and oncanplay to fix in angular 6

<video id="bg-video" loop muted autoplay oncanplay="this.play()" onloadedmetadata="this.muted = true">
    <source src="video.mp4" type="video/mp4">
</video>

Had a similar issue with Chrome 66 (OSX High Sierra) not autoplaying a muted video in a Mat Dialog being opened by its parent on init. Solved it by adding *ngIf="true" to the video element:

<video *ngIf="true" autoplay muted onloadedmetadata="this.muted = true" controls>
    <source src="myVid.mp4" type="video/mp4">
    <p>Your browser does not support the video element.</p>
</video>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!