webstaff: console logging for debugging audio
[Evergreen.git] / Open-ILS / web / js / ui / default / staff / services / audio.js
1 /**
2  * Core Service - egAudio
3  *
4  * Plays audio files by key name.  Each sound uses a dot-path to indicate 
5  * the sound.  
6  *
7  * For example:
8  * sound => 'warning.checkout.no_item'
9  * URLs are tested in the following order until a valid 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  * TODO: move audio file base path settings to the template 
17  * for configurability?
18  *
19  * Files are only played when sounds are configured to play via 
20  * workstation settings.
21  */
22
23 angular.module('egCoreMod')
24
25 .factory('egAudio', ['$q','egHatch', function($q, egHatch) {
26
27     var service = {
28         url_cache : {}, // map key names to audio file URLs
29         base_url : '/audio/notifications/'
30     };
31
32     /** 
33      * Play the sound found at the requested string path.  'path' is a 
34      * key name which maps to an audio file URL.
35      */
36     service.play = function(path) {
37         if (!path) return;
38         service.play_url(path, path);
39     }
40
41     service.play_url = function(path, orig_path) {
42         console.log('audio: play_url('+path+','+orig_path+')');
43
44         egHatch.getItem('eg.audio.disable').then(function(audio_disabled) {
45             if (!audio_disabled) {
46         
47                 var url = service.url_cache[path] || 
48                     service.base_url + path.replace(/\./g, '/') + '.wav';
49
50                 var player = new Audio(url);
51
52                 player.onloadeddata = function() {
53                     service.url_cache[orig_path] = url;
54                     player.play();
55                     console.log('audio: ' + url);
56                 };
57
58                 if (service.url_cache[path]) {
59                     // when serving from the cache, avoid secondary URL lookups.
60                     return;
61                 }
62
63                 player.onerror = function() {
64                     // Unable to play path at the requested URL.
65             
66                     if (!path.match(/\./)) {
67                         // all fall-through options have been exhausted.
68                         // No path to play.
69                         console.warn(
70                             "No suitable URL found for path '" + orig_path + "'");
71                         return;
72                     }
73
74                     // Fall through to the next (more generic) option
75                     path = path.replace(/\.[^\.]+$/, '');
76                     service.play_url(path, orig_path);
77                 }
78             }
79         });
80     }
81
82     return service;
83 }]);
84