changeset 52:ec38b85be3ac

Create publicly accessible streams for subscribing to play state change and seeking events.
author Lucas Thompson <dev@lucas.im>
date Wed, 07 Dec 2016 13:54:46 +0000
parents 8619f25ff52a
children ccfbce214751
files src/app/services/audio-player/audio-player.service.ts
diffstat 1 files changed, 23 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/src/app/services/audio-player/audio-player.service.ts	Tue Dec 06 14:19:03 2016 +0000
+++ b/src/app/services/audio-player/audio-player.service.ts	Wed Dec 07 13:54:46 2016 +0000
@@ -1,10 +1,29 @@
 import {Injectable, Inject} from '@angular/core';
+import {Subject} from "rxjs/Subject";
+import {Observable} from "rxjs";
 
 @Injectable()
 export class AudioPlayerService {
 
+  private currentObjectUrl: string;
+  private playingStateChange: Subject<boolean>;
+  playingStateChange$: Observable<boolean>;
+  private seeked: Subject<number>;
+  seeked$: Observable<number>;
+
   constructor(@Inject(HTMLAudioElement) private audioElement: HTMLAudioElement /* TODO probably shouldn't play audio this way */,
               @Inject('AudioContext') private audioContext: AudioContext) {
+    this.currentObjectUrl = '';
+    this.playingStateChange = new Subject<boolean>();
+    this.playingStateChange$ = this.playingStateChange.asObservable();
+    this.seeked = new Subject<number>();
+    this.seeked$ = this.seeked.asObservable();
+    this.audioElement.addEventListener('ended', () => {
+      this.playingStateChange.next(this.isPlaying());
+    });
+    this.audioElement.addEventListener('seeked', () => {
+      this.seeked.next(this.audioElement.currentTime);
+    });
   }
 
   getCurrentTime(): number {
@@ -20,12 +39,16 @@
   }
 
   loadAudioFromUrl(url: string): void {
+    if (this.currentObjectUrl)
+      URL.revokeObjectURL(this.currentObjectUrl);
+    this.currentObjectUrl = url;
     this.audioElement.pause();
     this.audioElement.src = url;
   }
 
   togglePlaying(): void {
     this.isPlaying() ? this.audioElement.pause() : this.audioElement.play();
+    this.playingStateChange.next(this.isPlaying());
   }
 
   setVolume(value: number): void {