-
Notifications
You must be signed in to change notification settings - Fork 3
/
JSonic.js
1338 lines (1255 loc) · 42.1 KB
/
JSonic.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* JSonic client-side API implemented using Dojo.
*
* :requires: Dojo 1.4.x, JSonic REST API on server
* :copyright: Peter Parente 2010, 2011 All Rights Reserved.
* :license: BSD
**/
/*global dojo dijit localStorage uow*/
dojo.provide('uow.audio.JSonic');
dojo.require('dijit._Widget');
// client api version
uow.audio._jsonicVersion = '0.5';
// singleton instance
uow.audio._jsonicInstance = null;
// factory to build a JSonic instance
uow.audio.initJSonic = function(args) {
if(!uow.audio._jsonicInstance) {
return new uow.audio.JSonic(args);
}
return uow.audio._jsonicInstance;
};
/**
* JSonic widget for application use.
*/
dojo.declare('uow.audio.JSonic', dijit._Widget, {
// root of the JSonic server REST API, defaults to / (read-only)
jsonicURI: '/',
// cache speech by default or not? defaults to false for privacy
defaultCaching: false,
// maximum size of the speech cache, defaults to 50 most recently used
cacheSize: 50,
constructor: function() {
if(uow.audio._jsonicInstance) {
throw new Error('JSonic instance already exists');
}
uow.audio._jsonicInstance = this;
},
postMixInProperties: function() {
// created audio channels
this._channels = {};
// channel-shared cache of sounds and speech
this._cache = new uow.audio.JSonicCache({
jsonicURI : this.jsonicURI,
cacheSize: this.cacheSize
});
},
/**
* Cleanup all resources on a destroy() call.
*/
uninitialize: function() {
for(var ch in this._channels) {
this._channels[ch].destroy();
}
this._cache.destroy();
uow.audio._jsonicInstance = null;
},
_setDefaultCachingAttr: function(value) {
this.defaultCaching = value;
},
/**
* Gets the version of the JSonic server API.
*
* :return: Deferred with a callback to get the version info
* :rtype: dojo.Deferred
*/
getServerVersion: function() {
var request = {
url : this.jsonicURI+'version',
headers : {
'Content-Type' : 'application/json;charset=UTF-8'
},
handleAs: 'json'
};
return dojo.xhrGet(request);
},
/**
* Gets the version of the JSonic client API.
*
* :return: Version
* :rtype: string
*/
getClientVersion: function() {
return uow.audio._jsonicVersion;
},
/**
* Queues speech on a channel. The args parameter supports the following
* name / value pairs.
*
* :param text: Text to speak.
* :type text: string
* :param channel: Channel name on which to queue the speech. Defaults to
* 'default'.
* :type channel: string
* :param name: Name to associate with the utterance. Included in any
* callbacks. Defaults to null.
* :type name: string
* :param cache: True to cache the utterance locally and track its
* frequency. False to avoid caching for privacy or other reasons.
* Defaults to the instance variable defaultCaching.
* :type cache: boolean
* :return: Object with 'before' and 'after' deferreds invoked just before
* speech starts and when it finishes (parameter: true) or is stopped
* (parameter: false).
* :rtype: object
*/
say: function(args) {
if(!args || !args.text) {
throw new Error('args.text required');
}
args.cache = (args.cache === undefined) ? this.defaultCaching : args.cache;
args.method = '_say';
args = this._getChannel(args.channel).push(args);
return args.defs;
},
/**
* Forces the server to synthesizes an utterance and return the URL to it.
* Useful for reducing latency when doing a later say if the utterance is
* known beforehand.
*
* The utterance adopts the properties of the channel as if it was queued
* behind all other commands on the channel. The synthesis starts
* immediately and does not block the next command queued on the channel.
* The resulting speech is not queued on the channel but is always cached.
*
* :param text: Text to synthesize as speech.
* :type text: string
* :param channel: Channel name on which to synth the speech. Defaults to
* 'default'.
* :type channel: string
* :return: Object with 'before' and 'after' deferreds invoked just before
* synth starts and when it finishes.
* :rtype: object
*/
synth: function(args) {
if(!args || !args.text) {
throw new Error('args.text required');
}
args.cache = true;
args.method = '_synth';
args = this._getChannel(args.channel).push(args);
return args.defs;
},
/**
* Queues sound on a channel. The args parameter supports the following
* name / value pairs.
*
* :param url: URL of the sound to play minus the extension. The extension
* is added properly based on the media type supported by the browser.
* (currently: .ogg or .mp3)
* :type url: string
* :param channel: Channel name on which to queue the sound. Defaults to
* 'default'.
* :type channel: string
* :param name: Name to associate with the sound. Included in any
* callbacks. Defaults to null.
* :type name: string
* :param cache: True to cache the utterance locally and track its
* frequency. False to avoid caching for privacy or other reasons.
* Defaults to the instance variable defaultCaching.
* :type cache: boolean
* :return: Object with 'before' and 'after' deferreds invoked just before
* sound starts and when it finishes (parameter: true) or is stopped
* (parameter: false).
* :rtype: object
*/
play: function(args) {
if(!args || !args.url) {
throw new Error('args.url required');
}
args.cache = (args.cache === undefined) ? this.defaultCaching : args.cache;
args.method = '_play';
args = this._getChannel(args.channel).push(args);
return args.defs;
},
/**
* Queues silence on the channel. The args parameter supports the following
* name / value pairs.
*
* :param duration: Duration of the period of silence in milliseconds.
* :type duration: int
* :param channel: Channel name on which to queue the silence. Defaults to
* 'default'.
* :type channel: string
* :param name: Name to associate with the silence. Included in any
* callbacks. Defaults to null.
* :type name: string
* :return: Object with 'before' and 'after' deferreds invoked just before
* silence starts and when it finishes (parameter: true) or is stopped
* (parameter: false).
* :rtype: object
*/
wait: function(args) {
if(!args || !args.duration) {
throw new Error('args.duration required');
}
args.method = '_wait';
args = this._getChannel(args.channel).push(args);
return args.defs;
},
/**
* Immediately pauses a channel. The args parameter supports the following
* name / value pairs.
*
* :param channel: Channel name to pause. Defaults to 'default'.
* :type channel: string
* :return: Object with 'before' and 'after' deferreds invoked just before
* pause starts and when it is in effect (true) or if it fails because
* the channel is already paused (false).
* :rtype: object
*/
pause: function(args) {
args = args || {};
args.method = '_pause';
args = this._getChannel(args.channel).push(args);
return args.defs;
},
/**
* Immediately unpauses a channel. The args parameter supports the following
* name / value pairs.
*
* :param channel: Channel name to pause. Defaults to 'default'.
* :type channel: string
* :return: Object with 'before' and 'after' deferreds invoked just before
* unpause starts and when takes effect (true) or if it fails because
* the channel is already unpaused (false).
* :rtype: object
*/
unpause: function(args) {
args = args || {};
args.method = '_unpause';
args = this._getChannel(args.channel).push(args);
return args.defs;
},
/**
* Immediately pauses all channels.
*
* :return: Objects with 'before' and 'after' deferreds invoked just before
* audio stops and right after.
* :rtype: array of object
*/
pauseAll: function() {
var rv = [];
for(var channel in this._channels) {
var args = {method : '_pause'};
this._channels[channel].push(args);
rv.push(args.defs);
}
return rv;
},
/**
* Immediately unpauses all channels.
*
* :return: Objects with 'before' and 'after' deferreds invoked just before
* audio stops and right after.
* :rtype: array of object
*/
unpauseAll: function() {
var rv = [];
for(var channel in this._channels) {
var args = {method : '_unpause'};
this._channels[channel].push(args);
rv.push(args.defs);
}
return rv;
},
/**
* Immediately stops output on a channel and clears the channel queue.
* The args parameter supports the following name / value pairs.
*
* :param channel: Channel name to stop. Defaults to 'default'.
* :type channel: string
* :return: Object with 'before' and 'after' deferreds invoked just before
* audio stops and right after.
* :rtype: object
*/
stop: function(args) {
args = args || {};
args.method = '_stop';
args = this._getChannel(args.channel).push(args);
return args.defs;
},
/**
* Immediately stops output on all channels and clears all channel queues.
*
* :return: Objects with 'before' and 'after' deferreds invoked just before
* audio stops and right after.
* :rtype: array of object
*/
stopAll: function() {
var rv = [];
for(var channel in this._channels) {
var args = {method : '_stop'};
this._channels[channel].push(args);
rv.push(args.defs);
}
return rv;
},
/**
* Executes or queues a change in channel property that affects all speech
* and sound output following it. All channels support the following
* properties:
*
* :rate: Speech rate in words per minute (default: 200)
* :pitch: Speech pitch between [0.0, 1.0] (default: 0.5)
* :volume: Speech and sound volume beteween [0.0, 1.0] (default: 1.0)
* :loop: Audio looping (default: false)
* :engine: Speech engine to use (default: espeak)
* :voice: Speech engine voice to use (default: default)
*
* A channel may support additional speech properties if they are named
* in the response from getEngineInfo.
*
* The args parameter supports the following name / value pairs.
*
* :param name: Name of the property to change.
* :type name: string
* :param value: Value to set for the property
* :type value: any
* :param immediate: Set properties immediately or when processed in the
* channel queue. (default: false)
* :type immediate: bool
* :param channel: Channel name on which to queue the change. Defaults to
* 'default'.
* :type channel: string
* :return: Object with 'before' and 'after' deferreds invoked just before
* speech the property is set (parameter: old property value) and right
* after (parameter: new property value).
* :rtype: object
*/
setProperty: function(args) {
if(!args || !args.name) {
throw new Error('args.name required');
}
args.method = '_setProperty';
args = this._getChannel(args.channel).push(args);
return args.defs;
},
/**
* Queues a request for the value of a channel property. If the property is
* unknown, undefined is returned.
*
* The args parameter supports the following name / value pairs.
*
* :param name: Name of the property value to fetch.
* :type name: string
* :param channel: Channel name on which to queue the fetch. Defaults to
* 'default'.
* :type channel: string
* :return: Object with 'before' and 'after' deferreds invoked immediately
* when the request is queued (parameter: current value) and after the
* request is processed (parameter: current value).
* :rtype: object
*/
getProperty: function(args) {
if(!args || !args.name) {
throw new Error('args.name required');
}
args.method = '_getProperty';
args = this._getChannel(args.channel).push(args);
return args.defs;
},
/**
* Queues a reset of all channel property values to their default values.
* The args parameter supports the following name / value pairs.
*
* :param channel: Channel name on which to queue the reset. Defaults to
* 'default'.
* :type channel: string
* :return: Object with 'before' and 'after' deferreds invoked just before
* the property reset (parameter: all old properties) and after the reset
* (parameter: reset property values).
* :rtype: object
*/
reset: function(args) {
args = args || {};
args.method = '_reset';
args = this._getChannel(args.channel).push(args);
return args.defs;
},
/**
* Queues a reset of all channel properties to their defaults on all
* channels.
*
* :return: Objects with 'before' and 'after' deferreds invoked just
* before the property reset (parameter: all old properties) and after
* the reset (parameter: reset property values) on each channel.
* :rtype: array of object
*/
resetAll: function() {
var rv = [];
for(var channel in this._channels) {
var args = {method : '_reset'};
this._channels[channel].push(args);
rv.push(args.defs);
}
return rv;
},
/**
* Gets the list of speech engine names available on the server.
*
* :return: Deferred with a callback to get the engine list
* :rtype: dojo.Deferred
*/
getEngines: function() {
return this._cache.getEngines();
},
/**
* Gets a description of the properties supported by a single speech engine
* available on the server.
*
* :return: Deferred with a callback to get the engine properties
* :rtype: dojo.Deferred
*/
getEngineInfo: function(name) {
return this._cache.getEngineInfo(name);
},
/**
* Adds an observer for channel events.
*
* :param func: Callback function to invoke on channel events.
* :type func: function
* :param channel: Channel name to observe. Defaults to 'default'.
* :type channel: string
* :param actions: Event names to observe. Defaults to all events if
* undefined.
* :type actions: array
* :return: Token to use when removing the observer
* :rtype: object
*/
addObserver: function(func, channel, actions) {
var ob = this._getChannel(channel).addObserver(func, actions);
return [ob, channel];
},
/**
* Removes an observer of channel events.
*
* :param token: Token returned when registering the observer
* :type token: object
*/
removeObserver: function(token) {
this._getChannel(token[1]).removeObserver(token[0]);
},
_getChannel: function(id) {
id = id || 'default';
var ch = this._channels[id];
if(ch === undefined) {
ch = new uow.audio.JSonicChannel({
id : 'jsonic.'+id,
cache : this._cache
});
this._channels[id] = ch;
}
return ch;
}
});
/**
* Helper class. Contains two dojo.Deferreds for callbacks and errbacks before
* and after a command is processed. Instances returned by many methods in
* uow.audio.JSonic.
*/
dojo.declare('uow.audio.JSonicDeferred', null, {
constructor: function() {
this.before = new dojo.Deferred();
this.after = new dojo.Deferred();
},
/**
* Shortcut for this.before.addCallback.
*
* :return: This instance for call chaining.
*/
callBefore: function(callback) {
this.before.addCallback(callback);
return this;
},
/**
* Shortcut for this.after.addCallback.
*
* :return: This instance for call chaining.
*/
callAfter: function(callback) {
this.after.addCallback(callback);
return this;
},
/**
* Shortcut for this.before.addErrback.
*
* :return: This instance for call chaining.
*/
errBefore: function(callback) {
this.before.addErrback(callback);
return this;
},
/**
* Shortcut for this.after.addErrback.
*
* :return: This instance for call chaining.
*/
errAfter: function(callback) {
this.after.addErrback(callback);
return this;
},
/**
* Shortcut for this.before.addBoth.
*
* :return: This instance for call chaining.
*/
anyBefore: function(callback) {
this.before.addBoth(callback);
return this;
},
/**
* Shortcut for this.after.addBoth.
*
* :return: This instance for call chaining.
*/
anyAfter: function(callback) {
this.after.addBoth(callback);
return this;
}
});
dojo.declare('uow.audio.LRUCache', null, {
constructor: function(args) {
this.maxSize = args.maxSize;
this.size = 0;
this._head = null;
this._tail = null;
this._index = {};
},
toArray: function() {
var curr = this._head;
var arr = [];
while(curr) {
arr.push([curr.key, curr.value]);
curr = curr.next;
}
return arr;
},
fromArray: function(arr) {
for(var i=0, l=arr.length; i < l; i++) {
var node = arr[i];
this.push(node[0], node[1]);
}
},
get: function(key) {
var node = this._index[key];
if(node) {
return node.value;
}
},
push: function(key, value) {
console.log('pushing', key);
// see if the key is already in the cache
var curr = this._index[key];
if(curr) {
// if so, remove it from the list
if(curr === this._head) {
this._head = curr.next;
}
if(curr === this._tail) {
this._tail = curr.prev;
}
if(curr.next) {
curr.next.prev = curr.prev;
delete curr.next;
}
if(curr.prev) {
curr.prev.next = curr.next;
delete curr.prev;
}
// update value
curr.value = value;
} else {
// if not, create a node for it
curr = {
key : key,
value : value
};
this._index[key] = curr;
this.size++;
}
if(!this._head) {
// set the first node as the head and tail
this._head = curr;
this._tail = curr;
} else {
// put it at the tail
this._tail.next = curr;
curr.prev = this._tail;
this._tail = curr;
}
// check if the cache is bigger than the max
if(this.size > this.maxSize) {
// pop the head
curr = this._head;
this._head = curr.next;
if(this._tail === curr) {
this._tail = null;
}
this.size--;
return curr;
}
return null;
}
});
/**
* Private. Shared cache implementation for JSonic.
*/
dojo.declare('uow.audio.JSonicCache', dijit._Widget, {
jsonicURI: null,
cacheSize: 50,
postMixInProperties: function() {
// speech engines and their details
this._engineCache = null;
// cache of speech filenames
this._speechCache = new uow.audio.LRUCache({maxSize : this.cacheSize});
if(localStorage) {
var arr = this._unserialize();
this._speechCache.fromArray(arr);
// register to persist on page unload
dojo.addOnUnload(this, '_serialize');
}
// cache of requests for speech rendering in progress
this._speechRenderings = {};
// determine extension to use
var node = dojo.create('audio');
if(node.canPlayType('audio/ogg') && node.canPlayType('audio/ogg') !== 'no') {
this._ext = '.ogg';
} else if(node.canPlayType('audio/mpeg') && node.canPlayType('audio/mpeg') !== 'no') {
this._ext = '.mp3';
} else {
throw new Error('no known media supported');
}
},
uninitialize: function() {
// persist cache before cleanup
this._serialize();
this._destroyed = true;
},
_serialize: function() {
if(this._destroyed) {
// don't persist if instance is destroyed
return;
}
localStorage['jsonic.cache'] = dojo.toJson(this._speechCache.toArray());
},
_unserialize: function() {
// clear the cache if versions don't match
if(localStorage['jsonic.version'] !== uow.audio._jsonicVersion) {
// reset the cache
this.resetCache();
}
// warm the cache from localStorage
try {
return dojo.fromJson(localStorage['jsonic.cache']) || [];
} catch(e) {
return [];
}
},
resetCache: function() {
if(localStorage) {
// clear out the cache
delete localStorage['jsonic.cache'];
// update the version number
localStorage['jsonic.version'] = uow.audio._jsonicVersion;
}
this._speechCache = new uow.audio.LRUCache({maxSize : this.maxSize});
},
getEngines: function() {
var request, def;
if(this._engineCache) {
def = new dojo.Deferred();
var names = [];
for(var key in this._engineCache) {
names.push(key);
}
def.callback(names);
} else {
request = {
url : this.jsonicURI+'engine',
handleAs: 'json',
headers : {
'Content-Type' : 'application/json;charset=UTF-8'
},
load: dojo.hitch(this, function(response) {
this._engineCache = {};
dojo.forEach(response.result, 'this._engineCache[item] = null;', this);
})
};
def = dojo.xhrGet(request);
}
return def;
},
getEngineInfo: function(name) {
var request, def;
if(this._engineCache[name]) {
def = new dojo.Deferred();
def.callback(this._engineCache[name]);
} else {
request = {
url : this.jsonicURI+'engine/'+name,
handleAs: 'json',
headers : {
'Content-Type' : 'application/json;charset=UTF-8'
},
load: dojo.hitch(this, function(response) {
this._engineCache[name] = response.result;
})
};
def = dojo.xhrGet(request);
}
return def;
},
getSound: function(args) {
var resultDef = new dojo.Deferred();
node = {}; //dojo.create('audio');
node.autobuffer = true;
node.src = args.url+this._ext;
resultDef.callback(node);
return resultDef;
},
_getSpeechCacheKey: function(text, props) {
var key = text;
var names = [];
// @todo: would be nice not to recompute every time, but how to
// store if we prefetch speech and are peeking into the queue?
for(var name in props) {
if(name === 'volume' || name === 'loop') {continue;}
names.push(name);
}
names.sort();
dojo.forEach(names, function(name) {
key += '.'+props[name];
});
return key;
},
getSpeech: function(args, props) {
// get the client cache key
var key = this._getSpeechCacheKey(args.text, props),
resultDef, audioNode, fileName, speechParams, request;
args.key = key;
// @todo: because we don't update lru upon each result, it's not
// truly lru; to meet strict definition, need to update stats
// when audio is actually used, not just when it's returned from
// the server; trying the simple way first, probably good enough
resultDef = this._speechRenderings[key];
if(resultDef) {
// return deferred result for synth already in progress on server
return resultDef;
}
fileName = this._speechCache.get(key);
if(fileName) {
console.log('known key', key);
// known key
this._speechCache.push(key, fileName);
audioNode = this._buildNode(fileName);
resultDef = new dojo.Deferred();
resultDef.callback(audioNode);
return resultDef;
}
// synth on server
speechParams = {
format : this._ext,
utterances : {text : args.text},
properties: props
};
resultDef = new dojo.Deferred();
request = {
url : this.jsonicURI+'synth',
handleAs: 'json',
postData : dojo.toJson(speechParams),
headers : {
'Content-Type' : 'application/json;charset=UTF-8'
},
load: dojo.hitch(this, '_onSpeechSynthed', resultDef, args),
error: dojo.hitch(this, '_onSynthError', resultDef, args)
};
dojo.xhrPost(request);
this._speechRenderings[key] = resultDef;
return resultDef;
},
_onSynthError: function(resultDef, args, err, ioargs) {
// clear request deferred
delete this._speechRenderings[args.key];
// get additional error info if possible
var desc;
try {
desc = dojo.fromJson(ioargs.xhr.responseText).description;
} catch(e) {
desc = '';
}
if(resultDef) {resultDef.errback(desc);}
return err;
},
_onSpeechSynthed: function(resultDef, args, response) {
delete this._speechRenderings[args.key];
var fileName = response.result.text;
var node = this._buildNode(fileName);
if(args.cache) {
// cache the speech file url and properties
this._speechCache.push(args.key, fileName);
}
resultDef.callback(node);
return node;
},
_buildNode: function(fileName) {
var node = {}; //dojo.create('audio');
node.autobuffer = true;
node.preload = 'auto';
node.src = this.jsonicURI+'files/'+fileName+this._ext;
return node;
}
});
/**
* Private. Independent speech / sound channel implementation for JSonic.
*/
dojo.declare('uow.audio.JSonicChannel', dijit._Widget, {
cache: null,
postMixInProperties: function() {
// current output, sound or speech
this._kind = null;
// optional name associated with current output
this._name = null;
// queue of commands to process
this._queue = [];
// busy processing a command or not
this._busy = false;
// arguments for the current audio
this._args = null;
// observers of callbacks on this channel
this._observers = [];
// current channel properties
this._properties = null;
// audio node in use by the channel
this._audioNode = null;
// audio node buffering data for playback
this._bufferNode = this._createNode();
// set default properties
this._reset();
},
uninitialize: function() {
this._args = null;
if(this._audioNode && !this._audioNode.paused) {
this._audioNode.pause();
}
if(this._args && this._args.timeout) {
clearTimeout(this._args.timeout);
}
dojo.forEach(this._aconnects, dojo.disconnect);
},
_createNode: function() {
var node = dojo.create('audio');
node.src = ''; // i* devices want us to touch this
node.load();
// callback tokens for the current audio node
this._aconnects = [];
this._aconnects[0] = dojo.connect(node, 'play', this, '_onStartMedia');
this._aconnects[1] = dojo.connect(node, 'pause', this, '_onPause');
this._aconnects[2] = dojo.connect(node, 'ended', this, '_onEndMedia');
this._aconnects[3] = dojo.connect(node, 'error', this, '_onMediaError');
return node;
},
push: function(args) {
// copy the args to avoid problems with reuse
args = dojo.clone(args);
// create deferred responses in the copy
args.defs = new uow.audio.JSonicDeferred();
if(args.method === '_setProperty' && args.immediate) {
// set property now
this._setProperty(args);
return args;
} else if(args.method === '_stop') {
// stop immediately
this._stop(args);
return args;
} else if(args.method === '_pause') {
this._pause(args);
return args;
} else if(args.method === '_unpause') {
this._unpause(args);
return args;
} else if(args.method === '_play') {
// pre-load sound
args.audio = this.cache.getSound(args);
} else if(args.method === '_say' || args.method === '_synth') {
// pre-synth speech with any props ahead in the queue
var props = dojo.clone(this._properties);
var changes = dojo.forEach(this._queue, function(args) {
if(args.method === '_setProperty') {
props[args.name] = args.value;
}
});
args.audio = this.cache.getSpeech(args, props);
if(args.method === '_synth') {
// trigger calls back to application
args.defs.before.callback();
args.audio.addCallback(args.defs.after.callback);
args.audio.addErrback(args.defs.after.errback);
// nothing to queue in the synth case
return args;
}
} else if(args.method === '_getProperty') {
args.defs.before.callback(this._properties[args.name]);
}
this._queue.push(args);
this._pump();
return args;
},
addObserver: function(func, actions) {
var ob = {func : func, actions : actions};
this._observers.push(ob);
return ob;
},
removeObserver: function(ob) {
var obs = this._observers;
for(var i=0; i < obs.length; i++) {
if(obs[i] === ob) {
this._observers = obs.slice(0, i).concat(obs.slice(i+1));
break;
}
}
},
_pump: function() {
while(!this._busy && this._queue.length) {
var args = this._queue.shift();
this._name = args.name;
this[args.method](args);
}
},
_playAudioNode: function(args, nodeProps) {
// don't play if we've stopped in the meantime
if(this._args !== args) {
return;
}
// set the properties on the node
var node = this._bufferNode;
dojo.mixin(node, nodeProps);
this._audioNode = node;
this._args.origSrc = node.src;