无法在Angular 7中播放MP4视频



我有两天的时间来处理一个关于angular 7中mp4视频的奇怪问题。由于某些原因,MP4视频根本无法播放。

这是我的代码:

HTML:

<div id="instructions" class="angled-img pull-left">
<video allow="autoplay" width="350px" height="195px" class="img" controls
poster='{{gameInfo.clip.preview}}'>
<source src="{{gameInfo.clip.clip}}" type='video/mp4' />
</video>
</div>

TS:

public gameInformation(id: number): void {
this.gameService.getGame(id).subscribe(res => {
this.gameInfo = res;
console.log(res);
this.loader = false;
}, error => {
console.error(error);
this.loader = false;
});
}

我不知道为什么会发生这种事。有人能帮我吗?我做错了什么。我正在使用ngx引导程序。

提前谢谢。

我可以在承诺中播放视频。在视频标签"静音">《自动播放》中使用这些属性。

此外,我还创建了stackblitz示例,其中我调用了一个伪http调用,并尝试播放示例视频。请在视频标签中使用ngIf="gameInfo">,以确保在渲染视频之前您的响应数据可用。此外,您还可以将视频播放包装在setTimeout中,以确保视频标记在页面中呈现。

这是stackblitz的工作示例。

使用角度播放视频

app.component.html

<hello name="{{ name }}"></hello>
<p>
Start editing to see some magic happen :)
</p>
<div id="instructions" class="angled-img pull-left">
<video muted autoplay  *ngIf="videoData" id="video1"  width="350px" height="195px" class="img" controls
>
<source src="{{videoData.url}}" type='video/mp4' />
</video>
</div>

应用程序组件.ts

import { Component,OnInit } from '@angular/core';
import { VideoService } from './video.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {
name = 'Angular';
videoData: any = {};
constructor(private videoService: VideoService) {
}
ngOnInit() {
this.videoService.getVideo().subscribe(data => {
this.videoData = data;
this.videoData.url = 'https://www.w3schools.com/html/mov_bbb.mp4';
setTimeout(() => {
document.getElementById('video1').play();
}, 1000);
}, (error) => {
this.videoData.url = 'https://www.w3schools.com/html/mov_bbb.mp4';
setTimeout(() => {
document.getElementById('video1').play();
}, 1000);

console.log('error', error)
})
}
}

视频服务.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators'
@Injectable()
export class VideoService {
private httpOptions = {
headers: new HttpHeaders({
'Content-Type':  'application/json'
})
};
url: string;
constructor(private http: HttpClient) { 
this.url = 'http://my-json-server.typicode.com/kodecrash/Javascript/video/1';
}
getVideo() {
return this.http.get<any>(this.url, this.httpOptions)
.pipe(map( (data: any) => {
// login successful if there's a jwt token in the response
return data;
}));
}
}

问题是chrome已经禁用了包含声音的视频的自动播放,因此,您需要使用静音和自动播放属性。尽管如此,视频可能不会自动播放,因为你需要在自动播放前静音才能使自动播放工作,但在编译过程中,angular会按字母顺序排列属性。因此,我发现了一个好的解决方案:

<video autoplay onloadedmetadata="this.muted = true" oncanplay="this.play()">
<source [src]="gameinfo.clip.clip" type="video/mp4" />
</video>

这样,视频将以角度自动播放,而不会更改typescript文件中的任何内容。

最新更新