我无法将当前时间分配给我的变量“ currentTime”,不知道如何找到一种解决方法以使该变量获取视频的当前时间?这似乎是关于范围变量的经典问题,但是我无法找到解决方案,有任何提示吗?谢谢!
import {Component, OnInit} from '@angular/core';
@Component({
selector: 'app-player',
templateUrl: './player.component.html',
styleUrls: ['./player.component.css']
})
export class PlayerComponent implements OnInit {
currentTime = 0;
ngOnInit() {
let player;
let myTimer;
window['onYouTubeIframeAPIReady'] = function () {
player = new window['YT'].Player('video', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerReady
}
});
};
function onPlayerReady(event) {
event.target.playVideo();
}
function onPlayerStateChange(event) {
if (event.data === 1) { // playing
myTimer = setInterval(() => {
const time = player.getCurrentTime();
console.log(time); // I want to set the currentTime declared on top equal to player.getCurrentTime();
}, 100);
} else { // not playing
clearInterval(myTimer);
}
}
if (!window['YT']) {
const tag = document.createElement('script');
tag.src = '//www.youtube.com/player_api';
const firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
}
constructor() {
}
}
感谢您的所有回复,我以经典的技巧完成了此操作,但是在阅读了How to access the correct `this` inside a callback?之后,使用了bind函数结束了。 该代码的怪异之处在于,如果没有'checkCurrentTime'间隔,则currentTime不会在html布局上更新,因此绝对不理解为什么。
import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';
@Component({
selector: 'app-player',
templateUrl: './player.component.html',
styleUrls: ['./player.component.css']
})
export class PlayerComponent implements OnInit, AfterViewInit {
tempoAttuale = 0;
ngAfterViewInit() {
let player;
let myTimer;
window['onYouTubeIframeAPIReady'] = function () {
player = new window['YT'].Player('video', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
};
function onPlayerReady(event) {
event.target.playVideo();
}
const tis = this;
function onPlayerStateChange(event) {
if (event.data === 1) { // playing
myTimer = setInterval(() => {
const time = player.getCurrentTime();
tis.tempoAttuale = time;
}, 100);
} else { // not playing
clearInterval(myTimer);
}
}
/*
I don't know why, but thanks to that the value of 'tempoAttuale' time on html is updated
*/
const checkCurrentTime = setInterval(() => {
}, 100);
if (!window['YT']) {
const tag = document.createElement('script');
tag.src = '//www.youtube.com/player_api';
const firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
}
ngOnInit() {
}
constructor() {
}
}