@react-native-ohos/audio-toolkit 2.1.0-rc.1 → 2.1.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CHANGELOG.md +6 -136
  2. package/COMMITTERS.md +6 -6
  3. package/LICENSE +22 -22
  4. package/ReactNativeAudioToolkit.podspec +18 -18
  5. package/harmony/audio_toolkit/LICENSE +20 -20
  6. package/harmony/audio_toolkit/NOTICE +32 -32
  7. package/harmony/audio_toolkit/OAT.xml +37 -37
  8. package/harmony/audio_toolkit/README.OpenSource +10 -10
  9. package/harmony/audio_toolkit/README.md +16 -16
  10. package/harmony/audio_toolkit/build-profile.json5 +7 -7
  11. package/harmony/audio_toolkit/hvigorfile.ts +1 -1
  12. package/harmony/audio_toolkit/index.ets +24 -24
  13. package/harmony/audio_toolkit/oh-package.json5 +12 -12
  14. package/harmony/audio_toolkit/src/main/cpp/generated/RNOH/generated/BaseAudioToolkitPackage.h +76 -76
  15. package/harmony/audio_toolkit/src/main/cpp/generated/RNOH/generated/turbo_modules/RCTAudioPlayer.cpp +23 -23
  16. package/harmony/audio_toolkit/src/main/cpp/generated/RNOH/generated/turbo_modules/RCTAudioPlayer.h +16 -16
  17. package/harmony/audio_toolkit/src/main/cpp/generated/RNOH/generated/turbo_modules/RCTAudioRecorder.cpp +20 -20
  18. package/harmony/audio_toolkit/src/main/cpp/generated/RNOH/generated/turbo_modules/RCTAudioRecorder.h +16 -16
  19. package/harmony/audio_toolkit/src/main/cpp/generated/react/renderer/components/audio_toolkit/ComponentDescriptors.h +24 -24
  20. package/harmony/audio_toolkit/src/main/cpp/generated/react/renderer/components/audio_toolkit/EventEmitters.cpp +16 -16
  21. package/harmony/audio_toolkit/src/main/cpp/generated/react/renderer/components/audio_toolkit/EventEmitters.h +17 -17
  22. package/harmony/audio_toolkit/src/main/cpp/generated/react/renderer/components/audio_toolkit/Props.cpp +19 -19
  23. package/harmony/audio_toolkit/src/main/cpp/generated/react/renderer/components/audio_toolkit/Props.h +18 -18
  24. package/harmony/audio_toolkit/src/main/cpp/generated/react/renderer/components/audio_toolkit/ShadowNodes.cpp +17 -17
  25. package/harmony/audio_toolkit/src/main/cpp/generated/react/renderer/components/audio_toolkit/ShadowNodes.h +23 -23
  26. package/harmony/audio_toolkit/src/main/cpp/generated/react/renderer/components/audio_toolkit/States.cpp +16 -16
  27. package/harmony/audio_toolkit/src/main/cpp/generated/react/renderer/components/audio_toolkit/States.h +18 -18
  28. package/harmony/audio_toolkit/src/main/ets/AudioToolkitPackage.ts +50 -50
  29. package/harmony/audio_toolkit/src/main/ets/Logger.ts +63 -63
  30. package/harmony/audio_toolkit/src/main/ets/RNCAudioPlayerTurboModule.ts +518 -432
  31. package/harmony/audio_toolkit/src/main/ets/RNCAudioRecorderTurboModule.ts +260 -260
  32. package/harmony/audio_toolkit/src/main/ets/generated/components/ts.ts +5 -5
  33. package/harmony/audio_toolkit/src/main/ets/generated/index.ets +5 -5
  34. package/harmony/audio_toolkit/src/main/ets/generated/ts.ts +6 -6
  35. package/harmony/audio_toolkit/src/main/ets/generated/turboModules/RCTAudioPlayer.ts +40 -40
  36. package/harmony/audio_toolkit/src/main/ets/generated/turboModules/RCTAudioRecorder.ts +24 -24
  37. package/harmony/audio_toolkit/src/main/ets/generated/turboModules/ts.ts +6 -6
  38. package/harmony/audio_toolkit/src/main/module.json5 +6 -6
  39. package/harmony/audio_toolkit/src/main/resources/base/element/string.json +7 -7
  40. package/harmony/audio_toolkit/src/main/resources/en_US/element/string.json +7 -7
  41. package/harmony/audio_toolkit/src/main/resources/zh_CN/element/string.json +7 -7
  42. package/harmony/audio_toolkit/ts.ts +25 -25
  43. package/harmony/audio_toolkit.har +0 -0
  44. package/package.json +47 -47
  45. package/src/Player.js +329 -329
  46. package/src/PlayerModule.ts +51 -51
  47. package/src/Recorder.js +183 -183
  48. package/src/RecorderModule.ts +83 -83
  49. package/src/index.ts +5 -5
@@ -1,433 +1,519 @@
1
- /**
2
- * MIT License
3
- *
4
- * Copyright (C) 2024 Huawei Device Co., Ltd.
5
- *
6
- * Permission is hereby granted, free of charge, to any person obtaining a copy
7
- * of this software and associated documentation files (the "Software"), to deal
8
- * in the Software without restriction, including without limitation the rights
9
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
- * copies of the Software, and to permit persons to whom the Software is
11
- * furnished to do so, subject to the following conditions:
12
- *
13
- * The above copyright notice and this permission notice shall be included in all
14
- * copies or substantial portions of the Software.
15
- *
16
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
- * SOFTWARE.
23
- */
24
-
25
- import { TurboModule, type TurboModuleContext } from '@rnoh/react-native-openharmony/ts';
26
- import { type BusinessError } from '@ohos.base';
27
- import media from '@ohos.multimedia.media';
28
- import fs from '@ohos.file.fs';
29
- import logger from './Logger';
30
-
31
- interface PlayConfig {
32
- volume?: number;
33
- pan?: number;
34
- wakeLock?: boolean;
35
- duration?: number;
36
- looping?: boolean;
37
- speed?: number;
38
- autoDestroy?: boolean;
39
- continuesToPlayInBackground?: boolean;
40
- }
41
-
42
- interface PlayInfo {
43
- duration: number;
44
- position: number;
45
- }
46
-
47
- interface Error {
48
- err?: string;
49
- message?: string;
50
- }
51
-
52
- enum ConfigKey {
53
- LOOPING = 'looping',
54
- SPEED = 'speed',
55
- VOLUME = 'volume',
56
- INITIALIZED = 'initialized'
57
- }
58
-
59
- enum StateChange {
60
- IDLE = 'idle',
61
- INITIALIZED = 'initialized',
62
- PREPARED = 'prepared',
63
- PLAYING = 'playing',
64
- PAUSED = 'paused',
65
- COMPLETED = 'completed',
66
- STOPPED = 'stopped',
67
- RELEASED = 'released',
68
- }
69
-
70
- export class RCTAudioPlayerTurboModule extends TurboModule {
71
- private readonly SANDBOX_START = '/data/storage';
72
- private readonly FILE_MANAGER_START = 'file://';
73
- private readonly HTTP_START = 'http';
74
- private readonly FD_PATH = 'fd://';
75
- private playerMap: Map<number, media.AVPlayer> = new Map();
76
- private playConfigMap: Map<number, PlayConfig> = new Map();
77
- private playInfoMap: Map<number, PlayInfo> = new Map();
78
- private playSeekCallbacks: Map<number, (err: string | Error, result?: PlayInfo) => void> = new Map();
79
-
80
- constructor(protected ctx: TurboModuleContext) {
81
- super(ctx);
82
- this.ctx = ctx;
83
- this.onBackground();
84
- }
85
-
86
- setPlayer(playerId: number, player: media.AVPlayer): void {
87
- this.playerMap.set(playerId, player);
88
- }
89
-
90
- getPlayer(playerId: number): media.AVPlayer {
91
- const player = this.playerMap.get(playerId);
92
- return player;
93
- }
94
-
95
- applyConfig(playerId: number): void {
96
- const player = this.playerMap.get(playerId);
97
- const config = this.playConfigMap.get(playerId);
98
- if (!config || !player) {
99
- return;
100
- }
101
- if (player.state === ConfigKey.INITIALIZED) {
102
- return;
103
- }
104
- Object.keys(config).forEach(key => {
105
- if (key === ConfigKey.LOOPING) {
106
- player.loop = config[ConfigKey.LOOPING];
107
- } else if (key === ConfigKey.SPEED) {
108
- player.setSpeed(config[ConfigKey.SPEED]);
109
- } else if (key === ConfigKey.VOLUME) {
110
- player.setVolume(config[ConfigKey.VOLUME]);
111
- } else {
112
- logger.warn('no contain condition');
113
- }
114
- });
115
- }
116
-
117
- setConfig(playerId: number, config: PlayConfig): void {
118
- const oldConfig = this.playConfigMap.get(playerId) ?? {};
119
- Object.keys(config).forEach(key => {
120
- oldConfig[key] = config[key];
121
- });
122
- this.playConfigMap.set(playerId, oldConfig);
123
- }
124
-
125
- set(playerId: number, config: PlayConfig, next: (err: string, result: object) => void): void {
126
- const player = this.playerMap.get(playerId);
127
- if (!player) {
128
- next('not found player', {});
129
- return;
130
- }
131
- this.setConfig(playerId, config);
132
- logger.debug(`set config:${JSON.stringify(config)}`);
133
- this.applyConfig(playerId);
134
- next('', {});
135
- }
136
-
137
- onBackground(): void {
138
- this.ctx.rnInstance.subscribeToLifecycleEvents('BACKGROUND', () => {
139
- logger.debug(`app state is BACKGROUND`);
140
- this.pauseOnBackground();
141
- });
142
- }
143
-
144
- pauseOnBackground(): void {
145
- this.playConfigMap.forEach((config, playerId) => {
146
- if (!config.continuesToPlayInBackground) {
147
- const player = this.playerMap.get(playerId);
148
- if (player) {
149
- player.pause();
150
- this.toEmit(playerId, 'pause', {
151
- message: 'Playback paused due toBackground',
152
- });
153
- }
154
- }
155
- });
156
- }
157
-
158
- emit(name: string, data: object): void {
159
- this.ctx.rnInstance.emitDeviceEvent(name, data);
160
- }
161
-
162
- toEmit(playerId: number, name: string, data: object): void {
163
- this.emit(`RCTAudioPlayerEvent:${playerId}`, {
164
- event: name,
165
- data,
166
- });
167
- }
168
-
169
- setAVPlayerCallback(avPlayer: media.AVPlayer, playerId: number, next: (object?) => void): void {
170
- // seek操作结果回调函数
171
- avPlayer.on('seekDone', (seekDoneTime: number) => {
172
- logger.debug(`AVPlayer seek succeeded, seek time is ${seekDoneTime}`);
173
- });
174
- // error回调监听函数,当avPlayer在操作过程中出现错误时调用 reset接口触发重置流程
175
- avPlayer.on('error', (err: BusinessError) => {
176
- logger.debug(`Invoke avPlayer failed, code is ${err.code}, message is ${err.message}`);
177
- this.toEmit(playerId, 'error', {
178
- err: err.message,
179
- message: 'Harmony AVPlayer error',
180
- });
181
- avPlayer.reset(); // 调用reset重置资源,触发idle状态
182
- });
183
- // 状态机变化回调函数
184
- this.avPlayerStateChangeCallback(avPlayer, playerId, next);
185
- avPlayer.on('seekDone', () => {
186
- const call = this.playSeekCallbacks.get(playerId);
187
- if (call) {
188
- call(``, this.getInfo(playerId));
189
- this.playSeekCallbacks.delete(playerId);
190
- }
191
- this.toEmit(playerId, 'seeked', {
192
- message: 'seek completed',
193
- });
194
- });
195
-
196
- const initInfo: PlayInfo = {
197
- duration: 0,
198
- position: 0,
199
- };
200
- this.playInfoMap.set(playerId, initInfo);
201
- avPlayer.on('durationUpdate', (duration) => {
202
- logger.debug(`durationUpdate:${duration}`);
203
- const info = this.playInfoMap.get(playerId);
204
- if (info) {
205
- info.duration = duration;
206
- }
207
- });
208
-
209
- avPlayer.on('timeUpdate', (time) => {
210
- const info = this.playInfoMap.get(playerId);
211
- if (info) {
212
- info.position = time;
213
- }
214
- });
215
- avPlayer.on('audioInterrupt', (reason) => {
216
- logger.debug(`audioInterrupt start:${JSON.stringify(reason)}`);
217
- this.toEmit(playerId, 'forcePause', {
218
- message: 'lost audio focus, playback paused',
219
- });
220
- });
221
- this.endOfStreamCallback(avPlayer, playerId);
222
- }
223
-
224
- endOfStreamCallback(avPlayer: media.AVPlayer, playerId: number): void {
225
- avPlayer.on('endOfStream', () => {
226
- const config = this.playConfigMap.get(playerId);
227
- if (config?.looping) {
228
- this.toEmit(playerId, 'looped', {
229
- message: 'media playback looped',
230
- });
231
- }
232
- });
233
- }
234
-
235
- avPlayerStateChangeCallback(avPlayer: media.AVPlayer, playerId: number, next: (object?) => void): void {
236
- avPlayer.on('stateChange', async (state: string, reason: media.StateChangeReason) => {
237
- logger.debug(`stateChange:${state}`);
238
- switch (state) {
239
- case StateChange.IDLE: // 成功调用reset接口后触发该状态机上报
240
- avPlayer.release(); // 调用release接口销毁实例对象
241
- break;
242
- case StateChange.INITIALIZED: // avplayer 设置播放源后触发该状态上报
243
- avPlayer.prepare();
244
- break;
245
- case StateChange.PREPARED: // prepare调用成功后上报该状态机
246
- logger.debug(`prepared called.to and apply config and play`);
247
- this.applyConfig(playerId);
248
- next(null);
249
- break;
250
- case StateChange.PLAYING: // play成功调用后触发该状态机上报
251
- break;
252
- case StateChange.PAUSED: // pause成功调用后触发该状态机上报
253
- logger.debug('paused called.');
254
- break;
255
- case StateChange.COMPLETED: { // 播放结束后触发该状态机上报
256
- logger.debug('completed called.');
257
- avPlayer.seek(0);
258
- this.toEmit(playerId, 'ended', {
259
- message: 'play completed',
260
- });
261
- const config = this.playConfigMap.get(playerId);
262
- if (config?.autoDestroy) {
263
- this.destroy(playerId);
264
- }
265
- break;
266
- }
267
- case StateChange.STOPPED: // stop接口成功调用后触发该状态机上报
268
- logger.debug('Player state stopped called.');
269
- avPlayer.reset(); // 调用reset接口初始化avplayer状态
270
- break;
271
- case StateChange.RELEASED:
272
- break;
273
- default:
274
- break;
275
- }
276
- });
277
- }
278
-
279
- async createPlayer(pathStr: string, playerId: number, next: (object?) => void): Promise<void> {
280
- logger.debug(`createPlayer path:${pathStr}`);
281
- try {
282
- const avPlayer: media.AVPlayer = await media.createAVPlayer();
283
- this.setAVPlayerCallback(avPlayer, playerId, next);
284
- if (pathStr.startsWith(this.HTTP_START)) {
285
- avPlayer.url = pathStr;
286
- } else {
287
- let fdPath = this.FD_PATH;
288
- const context = this.ctx.uiAbilityContext;
289
- let path = `${context.filesDir}/${pathStr}`;
290
- if (pathStr.startsWith(this.SANDBOX_START) || pathStr.startsWith(this.FILE_MANAGER_START)) {
291
- path = pathStr;
292
- }
293
- logger.debug(`file path:${path}`);
294
- const file = await fs.open(path);
295
- fdPath = fdPath + file.fd;
296
- logger.debug(`fdPath:${fdPath}`);
297
- avPlayer.url = fdPath;
298
- }
299
- this.setPlayer(playerId, avPlayer);
300
- } catch (e) {
301
- logger.warn(`createPlayer err:${JSON.stringify(e)}`);
302
- }
303
- }
304
-
305
- getInfo(playerId: number): PlayInfo {
306
- const info = this.playInfoMap.get(playerId);
307
- return info;
308
- }
309
-
310
- getCurrentTime(playerId: number, callback: (err: string, result?: PlayInfo) => void): void {
311
- const info = this.playInfoMap.get(playerId);
312
- if (info) {
313
- callback('', info);
314
- } else {
315
- callback('not found player');
316
- }
317
- }
318
-
319
- prepare(playerId: number, path: string, option: PlayConfig, next: (object?) => void): void {
320
- logger.debug(`prepare start`);
321
- this.setConfig(playerId, option);
322
- this.createPlayer(path, playerId, next).then(() => {
323
- });
324
- }
325
-
326
- checkPlayer(playerId: number, next: (object?) => void): boolean {
327
- const hasPlayer = this.playerMap.has(playerId);
328
- if (hasPlayer) {
329
- return true;
330
- } else {
331
- logger.debug('not found player')
332
- let err: Error = {
333
- err: 'not found player',
334
- message: 'not found media player',
335
- };
336
- next?.(err);
337
- return false;
338
- }
339
- }
340
-
341
- async play(playerId: number, callback: (object?, result?: PlayInfo) => void): Promise<void> {
342
- try {
343
- logger.debug(`play start`);
344
- if (!this.checkPlayer(playerId, callback)) {
345
- return;
346
- }
347
- const player = this.getPlayer(playerId);
348
- await player.play();
349
- callback(null, this.getInfo(playerId));
350
- } catch (e) {
351
- let err: Error = {
352
- err: 'player function err',
353
- message: `player call play function err:${JSON.stringify(e)}`,
354
- };
355
- callback?.(err, this.getInfo(playerId));
356
- }
357
- }
358
-
359
- async pause(playerId: number, callback: (object?, result?: PlayInfo) => void): Promise<void> {
360
- logger.debug(`pause start`);
361
- if (!this.checkPlayer(playerId, callback)) {
362
- return;
363
- }
364
- const player = this.getPlayer(playerId);
365
- await player.pause();
366
- this.toEmit(playerId, 'pause', {
367
- message: 'player paused',
368
- });
369
- callback(null, this.getInfo(playerId));
370
- }
371
-
372
- async stop(playerId: number, callback: () => void): Promise<void> {
373
- logger.debug(`stop start`);
374
- if (!this.checkPlayer(playerId, callback)) {
375
- return;
376
- }
377
- const config = this.playConfigMap.get(playerId);
378
- const player = this.getPlayer(playerId);
379
- if (config?.autoDestroy) {
380
- await player.pause();
381
- this.destroy(playerId);
382
- callback();
383
- } else {
384
- const oldCall = this.playSeekCallbacks.get(playerId);
385
- if (oldCall) {
386
- let err: Error = {
387
- err: 'seekfail',
388
- message: 'stopped before seek operation counld finish',
389
- };
390
- oldCall(err);
391
- this.playSeekCallbacks.delete(playerId);
392
- }
393
- this.playSeekCallbacks.set(playerId, callback);
394
- player.seek(0);
395
- await player.pause();
396
- }
397
- }
398
-
399
- destroy(playerId: number, callback?: () => void): void {
400
- logger.debug(`destroy start`);
401
- const player = this.getPlayer(playerId);
402
- player?.release();
403
- this.playerMap.delete(playerId);
404
- this.playConfigMap.delete(playerId);
405
- this.playInfoMap.delete(playerId);
406
- this.playSeekCallbacks.delete(playerId);
407
- if (callback) {
408
- callback();
409
- }
410
- }
411
-
412
- resume(playerId: number, callback: () => void): void {
413
- this.play(playerId, callback);
414
- }
415
-
416
- async seek(playerId: number, position: number, callback: () => void): Promise<void> {
417
- logger.debug(`seekbar:${position}`);
418
- if (!this.checkPlayer(playerId, callback)) {
419
- return;
420
- }
421
- const player = this.getPlayer(playerId);
422
- const oldCall = this.playSeekCallbacks.get(playerId);
423
- if (oldCall) {
424
- let err: Error = {
425
- err: 'seekfail',
426
- };
427
- oldCall(err);
428
- this.playSeekCallbacks.delete(playerId);
429
- }
430
- this.playSeekCallbacks.set(playerId, callback);
431
- player.seek(position);
432
- }
1
+ /**
2
+ * MIT License
3
+ *
4
+ * Copyright (C) 2024 Huawei Device Co., Ltd.
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ import { TurboModule, type TurboModuleContext } from '@rnoh/react-native-openharmony/ts';
26
+ import { type BusinessError } from '@ohos.base';
27
+ import media from '@ohos.multimedia.media';
28
+ import fs from '@ohos.file.fs';
29
+ import logger from './Logger';
30
+ import { audio } from '@kit.AudioKit';
31
+
32
+ // Continuous background audio task is managed by the app's EntryAbility.
33
+ import avsession from '@ohos.multimedia.avsession';
34
+
35
+ interface PlayConfig {
36
+ volume?: number;
37
+ pan?: number;
38
+ wakeLock?: boolean;
39
+ duration?: number;
40
+ looping?: boolean;
41
+ speed?: number;
42
+ autoDestroy?: boolean;
43
+ continuesToPlayInBackground?: boolean;
44
+ }
45
+
46
+ interface PlayInfo {
47
+ duration: number;
48
+ position: number;
49
+ }
50
+
51
+ interface Error {
52
+ err?: string;
53
+ message?: string;
54
+ }
55
+
56
+ enum ConfigKey {
57
+ LOOPING = 'looping',
58
+ SPEED = 'speed',
59
+ VOLUME = 'volume',
60
+ INITIALIZED = 'initialized'
61
+ }
62
+
63
+ enum StateChange {
64
+ IDLE = 'idle',
65
+ INITIALIZED = 'initialized',
66
+ PREPARED = 'prepared',
67
+ PLAYING = 'playing',
68
+ PAUSED = 'paused',
69
+ COMPLETED = 'completed',
70
+ STOPPED = 'stopped',
71
+ RELEASED = 'released',
72
+ }
73
+
74
+ type BackgroundAudioTaskBridge = {
75
+ startAudioPlayback?: () => Promise<void>;
76
+ stopAudioPlayback?: () => Promise<void>;
77
+ };
78
+
79
+ const AUDIO_BG_BRIDGE_KEY: string = '__rnohAudioBackgroundTask';
80
+
81
+ function getBackgroundAudioTaskBridge(): BackgroundAudioTaskBridge | undefined {
82
+ return Reflect.get(globalThis, AUDIO_BG_BRIDGE_KEY) as BackgroundAudioTaskBridge | undefined;
83
+ }
84
+
85
+ export class RCTAudioPlayerTurboModule extends TurboModule {
86
+ private readonly SANDBOX_START = '/data/storage';
87
+ private readonly FILE_MANAGER_START = 'file://';
88
+ private readonly HTTP_START = 'http';
89
+ private readonly FD_PATH = 'fd://';
90
+ private playerMap: Map<number, media.AVPlayer> = new Map();
91
+ private playConfigMap: Map<number, PlayConfig> = new Map();
92
+ private playInfoMap: Map<number, PlayInfo> = new Map();
93
+ private playSeekCallbacks: Map<number, (err: string | Error, result?: PlayInfo) => void> = new Map();
94
+ private session!: avsession.AVSession;
95
+ private init: boolean = false;
96
+
97
+ constructor(protected ctx: TurboModuleContext) {
98
+ super(ctx);
99
+ this.ctx = ctx;
100
+ this.onBackground();
101
+ }
102
+
103
+ setPlayer(playerId: number, player: media.AVPlayer): void {
104
+ this.playerMap.set(playerId, player);
105
+ }
106
+
107
+ getPlayer(playerId: number): media.AVPlayer {
108
+ const player = this.playerMap.get(playerId);
109
+ return player;
110
+ }
111
+
112
+ applyConfig(playerId: number): void {
113
+ const player = this.playerMap.get(playerId);
114
+ const config = this.playConfigMap.get(playerId);
115
+ if (!config || !player) {
116
+ return;
117
+ }
118
+ if (player.state === ConfigKey.INITIALIZED) {
119
+ return;
120
+ }
121
+ Object.keys(config).forEach(key => {
122
+ if (key === ConfigKey.LOOPING) {
123
+ player.loop = config[ConfigKey.LOOPING];
124
+ } else if (key === ConfigKey.SPEED) {
125
+ player.setSpeed(config[ConfigKey.SPEED]);
126
+ } else if (key === ConfigKey.VOLUME) {
127
+ player.setVolume(config[ConfigKey.VOLUME]);
128
+ } else {
129
+ logger.warn('no contain condition');
130
+ }
131
+ });
132
+ }
133
+
134
+ setConfig(playerId: number, config: PlayConfig): void {
135
+ const oldConfig = this.playConfigMap.get(playerId) ?? {};
136
+ Object.keys(config).forEach(key => {
137
+ oldConfig[key] = config[key];
138
+ });
139
+ this.playConfigMap.set(playerId, oldConfig);
140
+ }
141
+
142
+ set(playerId: number, config: PlayConfig, next: (err: string, result: object) => void): void {
143
+ const player = this.playerMap.get(playerId);
144
+ if (!player) {
145
+ next('not found player', {});
146
+ return;
147
+ }
148
+ this.setConfig(playerId, config);
149
+ logger.debug(`set config:${JSON.stringify(config)}`);
150
+ this.applyConfig(playerId);
151
+ next('', {});
152
+ }
153
+
154
+ onBackground(): void {
155
+ // this.ctx.rnInstance.subscribeToLifecycleEvents('BACKGROUND', () => {
156
+ // logger.debug(`app state is BACKGROUND`);
157
+ // this.pauseOnBackground();
158
+ // });
159
+ }
160
+
161
+ pauseOnBackground(): void {
162
+ this.playConfigMap.forEach((config, playerId) => {
163
+ if (!config.continuesToPlayInBackground) {
164
+ const player = this.playerMap.get(playerId);
165
+ if (player) {
166
+ player.pause();
167
+ this.toEmit(playerId, 'pause', {
168
+ message: 'Playback paused due toBackground',
169
+ });
170
+ }
171
+ }
172
+ });
173
+ }
174
+
175
+ emit(name: string, data: object): void {
176
+ this.ctx.rnInstance.emitDeviceEvent(name, data);
177
+ }
178
+
179
+ toEmit(playerId: number, name: string, data: object): void {
180
+ this.emit(`RCTAudioPlayerEvent:${playerId}`, {
181
+ event: name,
182
+ data,
183
+ });
184
+ }
185
+
186
+ setAVPlayerCallback(avPlayer: media.AVPlayer, playerId: number, next: (object?) => void): void {
187
+ // seek操作结果回调函数
188
+ avPlayer.on('seekDone', (seekDoneTime: number) => {
189
+ logger.debug(`AVPlayer seek succeeded, seek time is ${seekDoneTime}`);
190
+ });
191
+ // error回调监听函数,当avPlayer在操作过程中出现错误时调用 reset接口触发重置流程
192
+ avPlayer.on('error', (err: BusinessError) => {
193
+ logger.debug(`Invoke avPlayer failed, code is ${err.code}, message is ${err.message}`);
194
+ this.toEmit(playerId, 'error', {
195
+ err: err.message,
196
+ message: 'Harmony AVPlayer error',
197
+ });
198
+ avPlayer.reset(); // 调用reset重置资源,触发idle状态
199
+ });
200
+ // 状态机变化回调函数
201
+ this.avPlayerStateChangeCallback(avPlayer, playerId, next);
202
+ avPlayer.on('seekDone', () => {
203
+ const call = this.playSeekCallbacks.get(playerId);
204
+ if (call) {
205
+ call(``, this.getInfo(playerId));
206
+ this.playSeekCallbacks.delete(playerId);
207
+ }
208
+ this.toEmit(playerId, 'seeked', {
209
+ message: 'seek completed',
210
+ });
211
+ });
212
+
213
+ const initInfo: PlayInfo = {
214
+ duration: 0,
215
+ position: 0,
216
+ };
217
+ this.playInfoMap.set(playerId, initInfo);
218
+ avPlayer.on('durationUpdate', (duration) => {
219
+ logger.debug(`durationUpdate:${duration}`);
220
+ const info = this.playInfoMap.get(playerId);
221
+ if (info) {
222
+ info.duration = duration;
223
+ }
224
+ });
225
+
226
+ avPlayer.on('timeUpdate', (time) => {
227
+ const info = this.playInfoMap.get(playerId);
228
+ if (info) {
229
+ info.position = time;
230
+ }
231
+ });
232
+ avPlayer.on('audioInterrupt', (reason) => {
233
+ logger.debug(`MMMMM audioInterrupt start:${JSON.stringify(reason)}`);
234
+ this.toEmit(playerId, 'forcePause', {
235
+ message: 'lost audio focus, playback paused',
236
+ });
237
+ });
238
+ this.endOfStreamCallback(avPlayer, playerId);
239
+ }
240
+
241
+ endOfStreamCallback(avPlayer: media.AVPlayer, playerId: number): void {
242
+ avPlayer.on('endOfStream', () => {
243
+ const config = this.playConfigMap.get(playerId);
244
+ if (config?.looping) {
245
+ this.toEmit(playerId, 'looped', {
246
+ message: 'media playback looped',
247
+ });
248
+ }
249
+ });
250
+ }
251
+
252
+ avPlayerStateChangeCallback(avPlayer: media.AVPlayer, playerId: number, next: (object?) => void): void {
253
+ avPlayer.on('stateChange', async (state: string, reason: media.StateChangeReason) => {
254
+ logger.debug(`stateChange:${state}`);
255
+ switch (state) {
256
+ case StateChange.IDLE: // 成功调用reset接口后触发该状态机上报
257
+ avPlayer.release(); // 调用release接口销毁实例对象
258
+ break;
259
+ case StateChange.INITIALIZED: // avplayer 设置播放源后触发该状态上报
260
+ avPlayer.audioRendererInfo = {
261
+ usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
262
+ rendererFlags: 0,
263
+ }
264
+ avPlayer.prepare();
265
+ break;
266
+ case StateChange.PREPARED: // prepare调用成功后上报该状态机
267
+ logger.debug(`prepared called.to and apply config and play`);
268
+ this.applyConfig(playerId);
269
+ next(null);
270
+ break;
271
+ case StateChange.PLAYING: // play成功调用后触发该状态机上报
272
+ break;
273
+ case StateChange.PAUSED: // pause成功调用后触发该状态机上报
274
+ logger.debug('paused called.');
275
+ break;
276
+ case StateChange.COMPLETED: { // 播放结束后触发该状态机上报
277
+ logger.debug('completed called.');
278
+ avPlayer.seek(0);
279
+ this.toEmit(playerId, 'ended', {
280
+ message: 'play completed',
281
+ });
282
+ const config = this.playConfigMap.get(playerId);
283
+ if (config?.autoDestroy) {
284
+ this.destroy(playerId);
285
+ }
286
+ break;
287
+ }
288
+ case StateChange.STOPPED: // stop接口成功调用后触发该状态机上报
289
+ logger.debug('Player state stopped called.');
290
+ avPlayer.reset(); // 调用reset接口初始化avplayer状态
291
+ break;
292
+ case StateChange.RELEASED:
293
+ break;
294
+ default:
295
+ break;
296
+ }
297
+ });
298
+ }
299
+
300
+ async startContinuousTask() {
301
+ const bridge: BackgroundAudioTaskBridge | undefined = getBackgroundAudioTaskBridge();
302
+ if (!bridge?.startAudioPlayback) {
303
+ logger.warn('Background audio task bridge not initialized (EntryAbility)');
304
+ return;
305
+ }
306
+ await bridge.startAudioPlayback();
307
+ }
308
+
309
+ OnContinuousTaskCancel() {
310
+ // Kept for backward compatibility; cancellation is handled in EntryAbility.
311
+ return;
312
+ }
313
+
314
+ OffContinuousTaskCancel() {
315
+ // Kept for backward compatibility.
316
+ return;
317
+ }
318
+
319
+ async stopContinuousTask(): Promise<void> {
320
+ const bridge: BackgroundAudioTaskBridge | undefined = getBackgroundAudioTaskBridge();
321
+ if (!bridge?.stopAudioPlayback) {
322
+ return;
323
+ }
324
+ await bridge.stopAudioPlayback();
325
+ }
326
+
327
+ async initFun() {
328
+ if (this.init) {
329
+ return
330
+ }
331
+
332
+ avsession.createAVSession(this.ctx.uiAbilityContext, 'MMMMM_SESSION_NAME', 'audio').then(async (data: avsession.AVSession) => {
333
+ this.session = data;
334
+ this.session.activate()
335
+ console.info(`MMMMMM CreateAVSession : SUCCESS : sessionId = ${this.session.sessionId}`);
336
+
337
+ let metadata: avsession.AVMetadata = {
338
+ assetId: '0', // 由应用指定,用于标识应用媒体库里的媒体。
339
+ title: 'TITLE',
340
+ mediaImage: 'IMAGE',
341
+ artist: 'ARTIST',
342
+ };
343
+ this.session.setAVMetadata(metadata).then(() => {
344
+ console.info(`MMMMMM SetAVMetadata successfully`);
345
+ }).catch((err: BusinessError) => {
346
+ console.error(`MMMMMM Failed to set AVMetadata. Code: ${err.code}, message: ${err.message}`);
347
+ });
348
+ }).catch((err: BusinessError) => {
349
+ console.error(`MMMMMM CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
350
+ });
351
+ this.init = true;
352
+ }
353
+
354
+ async createPlayer(pathStr: string, playerId: number, next: (object?) => void): Promise<void> {
355
+ logger.debug(`createPlayer path:${pathStr}`);
356
+ this.initFun();
357
+ try {
358
+ const avPlayer: media.AVPlayer = await media.createAVPlayer();
359
+ this.setAVPlayerCallback(avPlayer, playerId, next);
360
+ if (pathStr.startsWith(this.HTTP_START)) {
361
+ avPlayer.url = pathStr;
362
+ } else {
363
+ let fdPath = this.FD_PATH;
364
+ const context = this.ctx.uiAbilityContext;
365
+ let path = `${context.filesDir}/${pathStr}`;
366
+ if (pathStr.startsWith(this.SANDBOX_START) || pathStr.startsWith(this.FILE_MANAGER_START)) {
367
+ path = pathStr;
368
+ }
369
+ logger.debug(`file path:${path}`);
370
+ const file = await fs.open(path);
371
+ fdPath = fdPath + file.fd;
372
+ logger.debug(`fdPath:${fdPath}`);
373
+ avPlayer.url = fdPath;
374
+ }
375
+ this.setPlayer(playerId, avPlayer);
376
+ } catch (e) {
377
+ logger.warn(`createPlayer err:${JSON.stringify(e)}`);
378
+ }
379
+ }
380
+
381
+ getInfo(playerId: number): PlayInfo {
382
+ const info = this.playInfoMap.get(playerId);
383
+ return info;
384
+ }
385
+
386
+ getCurrentTime(playerId: number, callback: (err: string, result?: PlayInfo) => void): void {
387
+ const info = this.playInfoMap.get(playerId);
388
+ if (info) {
389
+ callback('', info);
390
+ } else {
391
+ callback('not found player');
392
+ }
393
+ }
394
+
395
+ prepare(playerId: number, path: string, option: PlayConfig, next: (object?) => void): void {
396
+ logger.debug(`prepare start`);
397
+ this.setConfig(playerId, option);
398
+ this.createPlayer(path, playerId, next).then(() => {
399
+ });
400
+ }
401
+
402
+ checkPlayer(playerId: number, next: (object?) => void): boolean {
403
+ const hasPlayer = this.playerMap.has(playerId);
404
+ if (hasPlayer) {
405
+ return true;
406
+ } else {
407
+ logger.debug('not found player')
408
+ let err: Error = {
409
+ err: 'not found player',
410
+ message: 'not found media player',
411
+ };
412
+ next?.(err);
413
+ return false;
414
+ }
415
+ }
416
+
417
+ async play(playerId: number, callback: (object?, result?: PlayInfo) => void): Promise<void> {
418
+ try {
419
+ logger.debug(`play start`);
420
+ if (!this.checkPlayer(playerId, callback)) {
421
+ return;
422
+ }
423
+ const player = this.getPlayer(playerId);
424
+ await player.play();
425
+
426
+ this.startContinuousTask();
427
+ let playbackState: avsession.AVPlaybackState = {
428
+ state: avsession.PlaybackState.PLAYBACK_STATE_PLAY,
429
+ };
430
+ await this.session.setAVPlaybackState(playbackState);
431
+
432
+ callback(null, this.getInfo(playerId));
433
+ } catch (e) {
434
+ let err: Error = {
435
+ err: 'player function err',
436
+ message: `player call play function err:${JSON.stringify(e)}`,
437
+ };
438
+ callback?.(err, this.getInfo(playerId));
439
+ }
440
+ }
441
+
442
+ async pause(playerId: number, callback: (object?, result?: PlayInfo) => void): Promise<void> {
443
+ logger.debug(`pause start`);
444
+ if (!this.checkPlayer(playerId, callback)) {
445
+ return;
446
+ }
447
+ const player = this.getPlayer(playerId);
448
+ await player.pause();
449
+ await this.stopContinuousTask();
450
+ this.toEmit(playerId, 'pause', {
451
+ message: 'player paused',
452
+ });
453
+ callback(null, this.getInfo(playerId));
454
+ }
455
+
456
+ async stop(playerId: number, callback: () => void): Promise<void> {
457
+ logger.debug(`stop start`);
458
+ if (!this.checkPlayer(playerId, callback)) {
459
+ return;
460
+ }
461
+ const config = this.playConfigMap.get(playerId);
462
+ const player = this.getPlayer(playerId);
463
+ if (config?.autoDestroy) {
464
+ await player.pause();
465
+ await this.stopContinuousTask();
466
+ this.destroy(playerId);
467
+ callback();
468
+ } else {
469
+ const oldCall = this.playSeekCallbacks.get(playerId);
470
+ if (oldCall) {
471
+ let err: Error = {
472
+ err: 'seekfail',
473
+ message: 'stopped before seek operation counld finish',
474
+ };
475
+ oldCall(err);
476
+ this.playSeekCallbacks.delete(playerId);
477
+ }
478
+ this.playSeekCallbacks.set(playerId, callback);
479
+ player.seek(0);
480
+ await player.pause();
481
+ await this.stopContinuousTask();
482
+ }
483
+ }
484
+
485
+ destroy(playerId: number, callback?: () => void): void {
486
+ logger.debug(`destroy start`);
487
+ const player = this.getPlayer(playerId);
488
+ player?.release();
489
+ this.playerMap.delete(playerId);
490
+ this.playConfigMap.delete(playerId);
491
+ this.playInfoMap.delete(playerId);
492
+ this.playSeekCallbacks.delete(playerId);
493
+ if (callback) {
494
+ callback();
495
+ }
496
+ }
497
+
498
+ resume(playerId: number, callback: () => void): void {
499
+ this.play(playerId, callback);
500
+ }
501
+
502
+ async seek(playerId: number, position: number, callback: () => void): Promise<void> {
503
+ logger.debug(`seekbar:${position}`);
504
+ if (!this.checkPlayer(playerId, callback)) {
505
+ return;
506
+ }
507
+ const player = this.getPlayer(playerId);
508
+ const oldCall = this.playSeekCallbacks.get(playerId);
509
+ if (oldCall) {
510
+ let err: Error = {
511
+ err: 'seekfail',
512
+ };
513
+ oldCall(err);
514
+ this.playSeekCallbacks.delete(playerId);
515
+ }
516
+ this.playSeekCallbacks.set(playerId, callback);
517
+ player.seek(position);
518
+ }
433
519
  }