]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/util/audio.service.ts
LP#1775466 Angular(6) base application
[working/Evergreen.git] / Open-ILS / src / eg2 / src / app / share / util / audio.service.ts
1 /**
2  * Plays audio files (alerts, generally) by key name.  Each sound uses a
3  * dot-path to indicate  the sound.
4  *
5  * For example:
6  *
7  * this.audio.play('warning.checkout.no_item');
8  *
9  * URLs are tested in the following order until an audio file is found
10  * or no other paths are left to check.
11  *
12  * /audio/notifications/warning/checkout/not_found.wav
13  * /audio/notifications/warning/checkout.wav
14  * /audio/notifications/warning.wav
15  *
16  * Files are only played when sounds are configured to play via
17  * workstation settings.
18  */
19 import {Injectable, EventEmitter} from '@angular/core';
20 import {ServerStoreService} from '@eg/core/server-store.service';
21 const AUDIO_BASE_URL = '/audio/notifications/';
22
23 @Injectable()
24 export class AudioService {
25
26     // map of requested audio path to resolved path
27     private urlCache: {[path: string]: string} = {};
28
29     constructor(private store: ServerStoreService) {}
30
31     play(path: string): void {
32         if (path) {
33             this.playUrl(path, path);
34         }
35     }
36
37     playUrl(path: string, origPath: string): void {
38         // console.debug(`audio: playUrl(${path}, ${origPath})`);
39
40         this.store.getItem('eg.audio.disable').then(audioDisabled => {
41             if (audioDisabled) { return; }
42
43             const url = this.urlCache[path] ||
44                 AUDIO_BASE_URL + path.replace(/\./g, '/') + '.wav';
45
46             const player = new Audio(url);
47
48             player.onloadeddata = () => {
49                 this.urlCache[origPath] = url;
50                 player.play();
51                 console.debug(`audio: ${url}`);
52             };
53
54             if (this.urlCache[path]) {
55                 // when serving from the cache, avoid secondary URL lookups.
56                 return;
57             }
58
59             player.onerror = () => {
60                 // Unable to play path at the requested URL.
61
62                 if (!path.match(/\./)) {
63                     // all fall-through options have been exhausted.
64                     // No path to play.
65                     console.warn(
66                         `No suitable URL found for path "${origPath}"`);
67                     return;
68                 }
69
70                 // Fall through to the next (more generic) option
71                 path = path.replace(/\.[^\.]+$/, '');
72                 this.playUrl(path, origPath);
73             };
74         });
75     }
76 }
77
78