This repository has been archived by the owner on Oct 3, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
309 lines (276 loc) · 8.84 KB
/
index.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
//import { NativeModules } from 'react-native';
//const { RNSoundExo } = NativeModules;
//export default RNSoundExo;
import { NativeModules, NativeEventEmitter } from 'react-native';
const resolveAssetSource = require("react-native/Libraries/Image/resolveAssetSource");
const _DEFAULT_PROGRESS_UPDATE_INTERVAL_MILLIS = 500;
const _DEFAULT_INITIAL_PLAYBACK_STATUS = {
positionMillis: 0,
progressUpdateIntervalMillis: _DEFAULT_PROGRESS_UPDATE_INTERVAL_MILLIS,
shouldPlay: false,
rate: 1.0,
shouldCorrectPitch: false,
volume: 1.0,
isMuted: false,
isLooping: false,
};
const _throwErrorIfValuesOutOfBoundsInStatus = (status) => {
if (typeof status.rate === 'number' && (status.rate < 0.0 || status.rate > 32.0)) {
throw new Error('Rate value must be between 0.0 and 32.0.');
}
if (typeof status.volume === 'number' && (status.volume < 0.0 || status.volume > 1.0)) {
throw new Error('Volume value must be between 0.0 and 1.0.');
}
};
const _getUnloadedStatus = (error = null) => {
const status = { isLoaded: false };
if (error) {
status.error = error;
}
return status;
};
const _getAssetFromPlaybackSource = (source) => {
if (source == null) {
return null;
}
let asset = resolveAssetSource(source);
return asset;
};
const _getNativeSourceFromSource = (source) => {
let uri = null;
let overridingExtension = null;
let asset = _getAssetFromPlaybackSource(source);
if (asset != null) {
uri = asset.localUri || asset.uri;
} else if (
source != null &&
typeof source !== 'number' &&
'uri' in source &&
typeof source.uri === 'string'
) {
uri = source.uri;
}
if (uri == null) {
return null;
}
if (
source != null &&
typeof source !== 'number' &&
'overrideFileExtensionAndroid' in source &&
typeof source.overrideFileExtensionAndroid === 'string'
) {
overridingExtension = source.overrideFileExtensionAndroid;
}
return { uri, overridingExtension };
};
const _getNativeSourceAndFullInitialStatusForLoadAsync = async (
source,
initialStatus,
) => {
// Get the native source
const nativeSource = _getNativeSourceFromSource(source);
//console.log('nativeSource ', nativeSource);
if (nativeSource == null) {
throw new Error('Cannot load null source!');
}
// Get the full initial status
const fullInitialStatus = initialStatus == null
? _DEFAULT_INITIAL_PLAYBACK_STATUS
: {
..._DEFAULT_INITIAL_PLAYBACK_STATUS,
...initialStatus,
};
_throwErrorIfValuesOutOfBoundsInStatus(fullInitialStatus);
//console.log('fullInitialStatus ', fullInitialStatus);
return { nativeSource, fullInitialStatus };
};
class Sound {
constructor() {
this._loaded = false;
this._loading = false;
this._key = -1;
this._subscriptions = [];
this._lastStatusUpdate = null;
this._lastStatusUpdateTime = null;
this._onPlaybackStatusUpdate = null;
this._coalesceStatusUpdatesInMillis = 100;
this._eventEmitter = new NativeEventEmitter(NativeModules.ExponentAV);
}
static create = async (
source,
initialStatus = {},
onPlaybackStatusUpdate,
) => {
const sound = new Sound();
sound.setOnPlaybackStatusUpdate(onPlaybackStatusUpdate);
const status = await sound.loadAsync(source, initialStatus);
return { sound, status };
};
loadAsync = async (
source,
initialStatus = {},
) => {
if (this._loading) {
throw new Error('The Sound is already loading.');
}
if (!this._loaded) {
this._loading = true;
//console.log('start processing ', source);
const { nativeSource, fullInitialStatus }
= await _getNativeSourceAndFullInitialStatusForLoadAsync(source, initialStatus);
// This is a workaround, since using load with resolve / reject seems to not work.
return new Promise(
function (resolve, reject) {
const loadSuccess = (
key,
status,
) => {
this._key = key;
this._loaded = true;
this._loading = false;
NativeModules.ExponentAV.setErrorCallbackForSound(this._key, this._errorCallback);
this._subscribeToNativeStatusUpdateEvents();
this._callOnPlaybackStatusUpdateForNewStatus(status);
resolve(status);
};
const loadError = (error) => {
this._loading = false;
reject(new Error(error));
};
NativeModules.ExponentAV.loadForSound(
nativeSource,
fullInitialStatus,
loadSuccess,
loadError
);
}.bind(this)
);
} else {
throw new Error('The Sound is already loaded.');
}
};
async unloadAsync() {
if (this._loaded) {
this._loaded = false;
const key = this._key;
this._key = -1;
const status = await NativeModules.ExponentAV.unloadForSound(key);
this._callOnPlaybackStatusUpdateForNewStatus(status);
return status;
} else {
return this.getStatusAsync(); // Automatically calls onPlaybackStatusUpdate.
}
}
//API methods
async setStatusAsync(status) {
// console.error('Requested position after replay has to be 0.');
_throwErrorIfValuesOutOfBoundsInStatus(status);
return this._performOperationAndHandleStatusAsync(() =>
NativeModules.ExponentAV.setStatusForSound(this._key, status)
);
};
async playAsync() {
return this.setStatusAsync({ shouldPlay: true });
};
//{ toleranceMillisBefore?: number, toleranceMillisAfter?: number }
async playFromPositionAsync(positionMillis, tolerances = {}) {
return this.setStatusAsync({
positionMillis,
shouldPlay: true,
seekMillisToleranceAfter: tolerances.toleranceMillisAfter,
seekMillisToleranceBefore: tolerances.toleranceMillisBefore,
});
};
async setPositionAsync(positionMillis, tolerances = {}) {
return this.setStatusAsync({
positionMillis,
seekMillisToleranceAfter: tolerances.toleranceMillisAfter,
seekMillisToleranceBefore: tolerances.toleranceMillisBefore,
});
};
async replayAsync(status = {}) {
if (status.positionMillis && status.positionMillis !== 0) {
throw new Error('Requested position after replay has to be 0.');
}
return this.setStatusAsync({
...status,
positionMillis: 0,
shouldPlay: true,
});
};
async pauseAsync() {
console.log('pauseAsync clicked')
return this.setStatusAsync({ shouldPlay: false });
};
async stopAsync() {
return this.setStatusAsync({ positionMillis: 0, shouldPlay: false });
};
async setRateAsync(rate, shouldCorrectPitch) {
return this.setStatusAsync({ rate, shouldCorrectPitch });
};
async setVolumeAsync(volume) {
return this.setStatusAsync({ volume });
};
async setIsMutedAsync(isMuted) {
return this.setStatusAsync({ isMuted });
};
async setIsLoopingAsync(isLooping) {
return this.setStatusAsync({ isLooping });
};
async setProgressUpdateIntervalAsync(progressUpdateIntervalMillis) {
return this.setStatusAsync({ progressUpdateIntervalMillis });
};
//internal methods
_callOnPlaybackStatusUpdateForNewStatus(status) {
const shouldDismissBasedOnCoalescing =
this._lastStatusUpdateTime &&
JSON.stringify(status) === this._lastStatusUpdate &&
new Date() - this._lastStatusUpdateTime < this._coalesceStatusUpdatesInMillis;
if (this._onPlaybackStatusUpdate != null && !shouldDismissBasedOnCoalescing) {
this._onPlaybackStatusUpdate(status);
this._lastStatusUpdateTime = new Date();
this._lastStatusUpdate = JSON.stringify(status);
}
};
async _performOperationAndHandleStatusAsync(operation) {
if (this._loaded) {
const status = await operation();
this._callOnPlaybackStatusUpdateForNewStatus(status);
return status;
} else {
throw new Error('Cannot complete operation because sound is not loaded.');
}
};
_internalStatusUpdateCallback = ({ key, status }) => {
if (this._key === key) {
this._callOnPlaybackStatusUpdateForNewStatus(status);
}
};
// TODO: We can optimize by only using time observer on native if (this._onPlaybackStatusUpdate).
_subscribeToNativeStatusUpdateEvents() {
if (this._loaded) {
this._subscriptions.push(
this._eventEmitter.addListener(
'didUpdatePlaybackStatus',
this._internalStatusUpdateCallback
)
);
}
};
// Get status API
getStatusAsync = async () => {
if (this._loaded) {
return this._performOperationAndHandleStatusAsync(() =>
NativeModules.ExponentAV.getStatusForSound(this._key)
);
}
const status = _getUnloadedStatus();
this._callOnPlaybackStatusUpdateForNewStatus(status);
return status;
};
setOnPlaybackStatusUpdate(onPlaybackStatusUpdate) {
this._onPlaybackStatusUpdate = onPlaybackStatusUpdate;
this.getStatusAsync();
}
}
module.exports = Sound;