annotate src/app/services/render-loop/render-loop.service.ts @ 397:308ea1c2612e

Introduce a render loop service / singleton for work which needs to be animated with the play position. Use it for animating the cross-high. Much dupe with the live-play-head, which should be refactored.
author Lucas Thompson <dev@lucas.im>
date Fri, 02 Jun 2017 16:47:38 +0100
parents
children e06b62d949de
rev   line source
dev@397 1 /**
dev@397 2 * Created by lucast on 02/06/2017.
dev@397 3 */
dev@397 4 import {Injectable, NgZone} from '@angular/core';
dev@397 5 import {AudioPlayerService} from '../audio-player/audio-player.service';
dev@397 6 import {Subscription} from 'rxjs/Subscription';
dev@397 7 import {OnSeekHandler} from '../../playhead/PlayHeadHelpers';
dev@397 8
dev@397 9 @Injectable()
dev@397 10 export class RenderLoopService {
dev@397 11 private playingStateSubscription: Subscription;
dev@397 12 private seekedSubscription: Subscription;
dev@397 13 private tasks: OnSeekHandler[];
dev@397 14
dev@397 15 constructor(private player: AudioPlayerService,
dev@397 16 private zone: NgZone) {
dev@397 17 this.tasks = [];
dev@397 18 this.seekedSubscription = this.player.seeked$.subscribe(() => {
dev@397 19 if (!this.player.isPlaying()) {
dev@397 20 this.zone.runOutsideAngular(() => {
dev@397 21 this.runTasks();
dev@397 22 });
dev@397 23 }
dev@397 24 });
dev@397 25 this.playingStateSubscription = this.player.playingStateChange$.subscribe(
dev@397 26 isPlaying => {
dev@397 27 if (isPlaying) {
dev@397 28 this.animate();
dev@397 29 }
dev@397 30 });
dev@397 31 }
dev@397 32
dev@397 33 addPlayingTask(task: OnSeekHandler): void {
dev@397 34 this.tasks.push(task);
dev@397 35 }
dev@397 36
dev@397 37 private animate(): void {
dev@397 38 this.zone.runOutsideAngular(() => {
dev@397 39 const animateNextFrame = () => {
dev@397 40 if (this.player.isPlaying()) {
dev@397 41 this.runTasks();
dev@397 42 requestAnimationFrame(animateNextFrame);
dev@397 43 }
dev@397 44 };
dev@397 45 requestAnimationFrame(animateNextFrame);
dev@397 46 });
dev@397 47 }
dev@397 48
dev@397 49 private runTasks(): void {
dev@397 50 const currentTime = this.player.getCurrentTime();
dev@397 51 for (const task of this.tasks) {
dev@397 52 task(currentTime);
dev@397 53 }
dev@397 54 }
dev@397 55 }