I can't assign the current time to my variable 'currentTime', any idea how to get a workaround to let the variable get che current time of the video? it's seem a classic problem about scope variable, but i can't get a solution, any tips? thanks !
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() {
}
}
Thanks for all your responses, it's ended by me doing the classic this trick but after reading : How to access the correct `this` inside a callback?, It's ended using the bind function. The weird part of that code is that without the 'checkCurrentTime' interval the currentTime is not updated on html layout, definetly don't understand why.
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() {
}
}