forked from thinkpixellab/PxLoader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PxLoaderSound.js
96 lines (84 loc) · 2.89 KB
/
PxLoaderSound.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
/*global PxLoader: true, define: true, soundManager: true */
// PxLoader plugin to load sound using SoundManager2
function PxLoaderSound(id, url, tags, priority) {
var self = this,
loader = null;
this.tags = tags;
this.priority = priority;
this.sound = soundManager['createSound']({
'id': id,
'url': url,
'autoLoad': false,
'onload': function() {
loader.onLoad(self);
},
// HTML5-only event: Fires when a browser has chosen to stop downloading.
// "The user agent is intentionally not currently fetching media data,
// but does not have the entire media resource downloaded."
'onsuspend': function() {
loader.onTimeout(self);
},
// Fires at a regular interval when a sound is loading and new data
// has been received.
'whileloading': function() {
var bytesLoaded = this['bytesLoaded'],
bytesTotal = this['bytesTotal'];
// TODO: provide percentage complete updates to loader?
// see if we have loaded the file
if (bytesLoaded > 0 && (bytesLoaded === bytesTotal)) {
loader.onLoad(self);
}
}
});
this.start = function(pxLoader) {
// we need the loader ref so we can notify upon completion
loader = pxLoader;
// On iOS, soundManager2 uses a global audio object so we can't
// preload multiple sounds. We'll have to hope they load quickly
// when we need to play them. Unfortunately, SM2 doesn't expose
// a property to indicate its using a global object. For now we'll
// use the same test they do: only when on an iDevice
var iDevice = navigator.userAgent.match(/(ipad|iphone|ipod)/i);
if (iDevice) {
loader.onTimeout(self);
} else {
this.sound['load']();
}
};
this.checkStatus = function() {
switch(self.sound['readyState']) {
case 0:
// uninitialised
break;
case 1:
// loading
break;
case 2:
// failed/error
loader.onError(self);
break;
case 3:
// loaded/success
loader.onLoad(self);
break;
}
};
this.onTimeout = function() {
loader.onTimeout(self);
};
this.getName = function() {
return url;
};
}
// add a convenience method to PxLoader for adding a sound
PxLoader.prototype.addSound = function(id, url, tags, priority) {
var soundLoader = new PxLoaderSound(id, url, tags, priority);
this.add(soundLoader);
return soundLoader.sound;
};
// AMD module support
if (typeof define === 'function' && define.amd) {
define('PxLoaderSound', [], function() {
return PxLoaderSound;
});
}