1# @ohos.multimedia.audioHaptic (Audio-Haptic)
2
3Audio-haptic enables users to get rhythmic auditory and haptic feedback while having incoming calls or messages.
4
5> **NOTE**
6>
7> The initial APIs of this module are supported since API version 11. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8>
9
10## Modules to Import
11
12```ts
13import { audioHaptic } from '@kit.AudioKit';
14```
15
16## audioHaptic.getAudioHapticManager
17
18getAudioHapticManager(): AudioHapticManager
19
20Obtains an **AudioHapticManager** instance.
21
22**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
23
24**Return value**
25
26| Type                         | Description        |
27| ----------------------------- | ------------ |
28| [AudioHapticManager](#audiohapticmanager) | **AudioHapticManager** instance.|
29
30**Example**
31```ts
32let audioHapticManagerInstance: audioHaptic.AudioHapticManager = audioHaptic.getAudioHapticManager();
33```
34
35## AudioLatencyMode
36
37Enumerates the audio latency modes.
38
39**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
40
41| Name                           |  Value    | Description                                        |
42| ------------------------------- | ------ | -------------------------------------------- |
43| AUDIO_LATENCY_MODE_NORMAL       | 0      | Normal latency mode.                               |
44| AUDIO_LATENCY_MODE_FAST         | 1      | Low latency mode. This mode is applicable to short audio files. A long audio file may be truncated in this mode. It functions the same as [SoundPool](../apis-media-kit/js-apis-inner-multimedia-soundPool.md#soundpool).|
45
46## AudioHapticPlayerOptions
47
48Describes the options for the audio-haptic player.
49
50**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
51
52| Name     | Type           |Mandatory  | Description                             |
53| --------- | -------------- | ---- | --------------------------------- |
54| muteAudio   | boolean      | No  | Whether to mute the audio. The value **true** means to mute the audio, and **false** means the opposite. If this parameter is not specified, the default value **false** is used.|
55| muteHaptics | boolean      | No  | Whether to mute haptics feedback. The value **true** means to mute haptics feedback, and **false** means the opposite. If this parameter is not specified, the default value **false** is used.|
56
57## AudioHapticManager
58
59Manages the audio-haptic feature. Before calling any API in **AudioHapticManager**, you must use [getAudioHapticManager](#audiohapticgetaudiohapticmanager) to create an **AudioHapticManager** instance.
60
61### registerSource
62
63registerSource(audioUri: string, hapticUri: string): Promise<number>
64
65Registers an audio-haptic source. This API uses a promise to return the result.
66
67**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
68
69**Parameters**
70
71| Name  | Type                                     | Mandatory| Description                    |
72| -------- | ---------------------------------------- | ---- | ------------------------ |
73| audioUri  | string                                  | Yes  | URI of the audio source. In normal latency mode, the supported audio resource formats and path formats are defined in [media.AVPlayer](../apis-media-kit/js-apis-media.md#avplayer9). In low latency mode, the supported audio resource formats are defined in [SoundPool](../apis-media-kit/js-apis-inner-multimedia-soundPool.md#soundpool), and the path format must meet the requirements of [fs.open](../apis-core-file-kit/js-apis-file-fs.md#fsopen). In both modes, you are advised to pass in the absolute path of the file.          |
74| hapticUri | string                                  | Yes  | URI of the haptic source. The supported haptic resource formats are defined in [vibrator](../apis-sensor-service-kit/js-apis-vibrator.md#hapticfiledescriptor10). The path format must meet the requirements of [fs.open](../apis-core-file-kit/js-apis-file-fs.md#fsopen). You are advised to pass in the absolute path of the file.        |
75
76**Return value**
77
78| Type               | Description                           |
79| ------------------- | ------------------------------- |
80| Promise<number> | Promise used to return the source ID.|
81
82**Error codes**
83
84For details about the error codes, see [Media Error Codes](../apis-media-kit/errorcode-media.md).
85
86| ID| Error Message                             |
87| ------- |-----------------------------------|
88| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
89
90**Example**
91
92```ts
93import { BusinessError } from '@kit.BasicServicesKit';
94
95let audioUri = 'data/audioTest.wav'; // Change it to the URI of the target audio source.
96let hapticUri = 'data/hapticTest.json'; // Change it to the URI of the target haptic source.
97let id = 0;
98
99audioHapticManagerInstance.registerSource(audioUri, hapticUri).then((value: number) => {
100  console.info(`Promise returned to indicate that the source id of the registerd source ${value}.`);
101  id = value;
102}).catch ((err: BusinessError) => {
103  console.error(`Failed to register source ${err}`);
104});
105```
106
107### unregisterSource
108
109unregisterSource(id: number): Promise<void>
110
111Unregisters an audio-haptic source. This API uses a promise to return the result.
112
113**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
114
115**Parameters**
116
117| Name  | Type                                     | Mandatory| Description                    |
118| -------- | ---------------------------------------- | ---- | ------------------------ |
119| id       | number                                   | Yes  | Source ID.   |
120
121**Error codes**
122
123For details about the error codes, see [Media Error Codes](../apis-media-kit/errorcode-media.md).
124
125| ID| Error Message                             |
126| ------- |-----------------------------------|
127| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
128
129**Example**
130
131```ts
132import { BusinessError } from '@kit.BasicServicesKit';
133
134let audioUri = 'data/audioTest.wav'; // Change it to the URI of the target audio source.
135let hapticUri = 'data/hapticTest.json'; // Change it to the URI of the target haptic source.
136let id = 0;
137
138audioHapticManagerInstance.registerSource(audioUri, hapticUri).then((value: number) => {
139  console.info(`Promise returned to indicate that the source id of the registerd source ${value}.`);
140  id = value;
141}).catch ((err: BusinessError) => {
142  console.error(`Failed to register source ${err}`);
143});
144
145audioHapticManagerInstance.unregisterSource(id).then(() => {
146  console.info(`Promise returned to indicate that unregister source successfully`);
147}).catch ((err: BusinessError) => {
148  console.error(`Failed to unregistere source ${err}`);
149});
150```
151
152### setAudioLatencyMode
153
154setAudioLatencyMode(id:number, latencyMode: AudioLatencyMode): void
155
156Sets the latency mode for an audio-haptic source.
157
158**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
159
160**Parameters**
161
162| Name  | Type                                     | Mandatory| Description                    |
163| -------- | ---------------------------------------- | ---- | ------------------------ |
164| id          | number                                | Yes  | Source ID.   |
165| latencyMode | [AudioLatencyMode](#audiolatencymode) | Yes  | Audio latency mode.            |
166
167**Error codes**
168
169For details about the error codes, see [Media Error Codes](../apis-media-kit/errorcode-media.md).
170
171| ID| Error Message                             |
172| ------- |-----------------------------------|
173| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
174| 5400102 | Operation not allowed.            |
175
176**Example**
177
178```ts
179import { BusinessError } from '@kit.BasicServicesKit';
180
181let audioUri = 'data/audioTest.wav'; // Change it to the URI of the target audio source.
182let hapticUri = 'data/hapticTest.json'; // Change it to the URI of the target haptic source.
183let id = 0;
184
185audioHapticManagerInstance.registerSource(audioUri, hapticUri).then((value: number) => {
186  console.info(`Promise returned to indicate that the source id of the registerd source ${value}.`);
187  id = value;
188}).catch ((err: BusinessError) => {
189  console.error(`Failed to register source ${err}`);
190});
191
192let latencyMode: audioHaptic.AudioLatencyMode = audioHaptic.AudioLatencyMode.AUDIO_LATENCY_MODE_FAST;
193
194audioHapticManagerInstance.setAudioLatencyMode(id, latencyMode);
195```
196
197### setStreamUsage
198
199setStreamUsage(id: number, usage: audio.StreamUsage): void
200
201Sets the stream usage for an audio-haptic source.
202
203**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
204
205**Parameters**
206
207| Name  | Type                                     | Mandatory| Description                    |
208| -------- | ---------------------------------------- | ---- | ------------------------ |
209| id       | number                                   | Yes  | Source ID.   |
210| usage    | [audio.StreamUsage](js-apis-audio.md#streamusage) | Yes  | Stream usage.   |
211
212**Error codes**
213
214For details about the error codes, see [Media Error Codes](../apis-media-kit/errorcode-media.md).
215
216| ID| Error Message                             |
217| ------- |-----------------------------------|
218| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3.Parameter verification failed. |
219| 5400102 | Operation not allowed.            |
220
221**Example**
222
223```ts
224import { audio } from '@kit.AudioKit';
225import { BusinessError } from '@kit.BasicServicesKit';
226
227let audioUri = 'data/audioTest.wav'; // Change it to the URI of the target audio source.
228let hapticUri = 'data/hapticTest.json'; // Change it to the URI of the target haptic source.
229let id = 0;
230
231audioHapticManagerInstance.registerSource(audioUri, hapticUri).then((value: number) => {
232  console.info(`Promise returned to indicate that the source id of the registerd source ${value}.`);
233  id = value;
234}).catch ((err: BusinessError) => {
235  console.error(`Failed to register source ${err}`);
236});
237
238let usage: audio.StreamUsage = audio.StreamUsage.STREAM_USAGE_NOTIFICATION;
239
240audioHapticManagerInstance.setStreamUsage(id, usage);
241```
242
243### createPlayer
244
245createPlayer(id: number, options?: AudioHapticPlayerOptions): Promise<AudioHapticPlayer>
246
247Creates an audio-haptic player. This API uses a promise to return the result.
248
249**Required permissions**: ohos.permission.VIBRATE
250
251If the audio-haptic player needs to trigger vibration, check whether the application has the permission.
252
253**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
254
255**Parameters**
256
257| Name  | Type                                     | Mandatory| Description                    |
258| -------- | ---------------------------------------- | ---- | ------------------------ |
259| id       | number                                   | Yes  | Source ID.   |
260| options  | [AudioHapticPlayerOptions](#audiohapticplayeroptions) | No  | Options of the audio-haptic player.|
261
262**Return value**
263
264| Type               | Description                           |
265| ------------------- | ------------------------------- |
266| Promise<[AudioHapticPlayer](#audiohapticplayer)> | Promise used to return the audio-haptic player.|
267
268**Error codes**
269
270For details about the error codes, see [Media Error Codes](../apis-media-kit/errorcode-media.md).
271
272| ID| Error Message                             |
273| ------- |-----------------------------------|
274| 201 | Permission denied. |
275| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
276| 5400102 | Operation not allowed. |
277| 5400103 | I/O error. |
278| 5400106 | Unsupport format. |
279
280**Example**
281
282```ts
283import { BusinessError } from '@kit.BasicServicesKit';
284
285let audioUri = 'data/audioTest.wav'; // Change it to the URI of the target audio source.
286let hapticUri = 'data/hapticTest.json'; // Change it to the URI of the target haptic source.
287let id = 0;
288
289audioHapticManagerInstance.registerSource(audioUri, hapticUri).then((value: number) => {
290  console.info(`Promise returned to indicate that the source id of the registerd source ${value}.`);
291  id = value;
292}).catch ((err: BusinessError) => {
293  console.error(`Failed to register source ${err}`);
294});
295
296let options: audioHaptic.AudioHapticPlayerOptions = {muteAudio: false, muteHaptics: false};
297let audioHapticPlayerInstance: audioHaptic.AudioHapticPlayer | undefined = undefined;
298
299audioHapticManagerInstance.createPlayer(id, options).then((value: audioHaptic.AudioHapticPlayer) => {
300  audioHapticPlayerInstance = value;
301  console.info(`Create the audio haptic player successfully.`);
302}).catch ((err: BusinessError) => {
303  console.error(`Failed to create the audio haptic player. ${err}`);
304});
305```
306
307## AudioHapticType
308
309Enumerates the audio haptic types.
310
311**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
312
313| Name                           |  Value    | Description                                        |
314| ------------------------------- | ------ | -------------------------------------------- |
315| AUDIO_HAPTIC_TYPE_AUDIO         | 0      | Audio.                                   |
316| AUDIO_HAPTIC_TYPE_HAPTIC        | 1      | Haptic.                                   |
317
318## AudioHapticPlayer
319
320Implements audio-haptic playback. Before calling any API in **AudioHapticPlayer**, you must use [createPlayer](#createplayer) to create an **AudioHapticPlayer** instance.
321
322### isMuted
323
324isMuted(type: AudioHapticType): boolean
325
326Checks whether an audio-haptic type is muted.
327
328**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
329
330**Parameters**
331
332| Name  | Type                                     | Mandatory| Description                    |
333| -------- | ---------------------------------------- | ---- | ------------------------ |
334| type     | [AudioHapticType](#audiohaptictype)      | Yes  | Audio-haptic type.               |
335
336**Return value**
337
338| Type               | Description                           |
339| ------------------- | ------------------------------- |
340| boolean             | Whether the audio-haptic type is muted.       |
341
342**Error codes**
343
344For details about the error codes, see [Media Error Codes](../apis-media-kit/errorcode-media.md).
345
346| ID| Error Message                             |
347| ------- |-----------------------------------|
348| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Parameter verification failed. |
349
350**Example**
351
352```ts
353let audioHapticType: audioHaptic.AudioHapticType = audioHaptic.AudioHapticType.AUDIO_HAPTIC_TYPE_AUDIO;
354
355let result: boolean = audioHapticPlayerInstance.isMuted(audioHapticType);
356```
357
358### start
359
360start(): Promise<void>
361
362Starts playing the audio and haptic source. This API uses a promise to return the result.
363
364**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
365
366**Return value**
367
368| Type               | Description                             |
369| ------------------- | -------------------------------- |
370| Promise<void> | Promise used to return the result.|
371
372**Error codes**
373
374For details about the error codes, see [Media Error Codes](../apis-media-kit/errorcode-media.md).
375
376| ID  | Error Message                             |
377|---------|-----------------------------------|
378| 5400102 | Operate not permit. |
379| 5400103 | IO error. |
380| 5400105 | Service died. |
381
382
383**Example**
384
385```ts
386import { BusinessError } from '@kit.BasicServicesKit';
387
388audioHapticPlayerInstance.start().then(() => {
389  console.info(`Promise returned to indicate that start playing successfully.`);
390}).catch ((err: BusinessError) => {
391  console.error(`Failed to start playing. ${err}`);
392});
393```
394
395### stop
396
397stop(): Promise<void>
398
399Stops playing the audio-haptic source. This API uses a promise to return the result.
400
401**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
402
403**Return value**
404
405| Type               | Description                             |
406| ------------------- | -------------------------------- |
407| Promise<void> | Promise used to return the result.|
408
409**Error codes**
410
411For details about the error codes, see [Media Error Codes](../apis-media-kit/errorcode-media.md).
412
413| ID  | Error Message                             |
414|---------|-----------------------------------|
415| 5400102 | Operate not permit. |
416| 5400105 | Service died. |
417
418**Example**
419
420```ts
421import { BusinessError } from '@kit.BasicServicesKit';
422
423audioHapticPlayerInstance.stop().then(() => {
424  console.info(`Promise returned to indicate that stop playing successfully.`);
425}).catch ((err: BusinessError) => {
426  console.error(`Failed to stop playing. ${err}`);
427});
428```
429
430### release
431
432release(): Promise<void>
433
434Releases this audio-haptic player. This API uses a promise to return the result.
435
436**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
437
438**Return value**
439
440| Type               | Description                           |
441| ------------------- | ------------------------------- |
442| Promise<void> | Promise used to return the result.  |
443
444**Error codes**
445
446For details about the error codes, see [Media Error Codes](../apis-media-kit/errorcode-media.md).
447
448| ID  | Error Message                             |
449|---------|-----------------------------------|
450| 5400105 | Service died. |
451
452**Example**
453
454```ts
455import { BusinessError } from '@kit.BasicServicesKit';
456
457audioHapticPlayerInstance.release().then(() => {
458  console.info(`Promise returned to indicate that release the audio haptic player successfully.`);
459}).catch ((err: BusinessError) => {
460  console.error(`Failed to release the audio haptic player. ${err}`);
461});
462```
463
464### on('endOfStream')
465
466on(type: 'endOfStream', callback: Callback<void>): void
467
468Subscribes to end of stream (EOS) event, which is triggered when the audio stream playback ends. This API uses an asynchronous callback to return the result.
469
470**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
471
472**Parameters**
473
474| Name  | Type                    | Mandatory| Description                                                                      |
475| -------- | ----------------------- | ---- | -------------------------------------------------------------------------- |
476| type     | string                  | Yes  | Event type. The value is fixed at **'endOfStream'**.|
477| callback | Callback<void>    | Yes  | Callback that returns no value.|
478
479**Example**
480
481```ts
482audioHapticPlayerInstance.on('endOfStream', () => {
483  console.info(`Receive the callback of endOfStream.`);
484});
485```
486
487### off('endOfStream')
488
489off(type: 'endOfStream', callback?: Callback<void>): void
490
491Unsubscribes from the EOS event. This API uses an asynchronous callback to return the result.
492
493**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
494
495**Parameters**
496
497| Name| Type  | Mandatory| Description                                             |
498| ----- | ----- | ---- | ------------------------------------------------ |
499| type   | string | Yes  | Event type. The value is fixed at **'endOfStream'**.|
500| callback | Callback<void>    | No  | Callback that returns no value.|
501
502**Example**
503
504```ts
505// Cancel all subscriptions to the event.
506audioHapticPlayerInstance.off('endOfStream');
507
508// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter.
509let endOfStreamCallback = () => {
510  console.info(`Receive the callback of endOfStream.`);
511};
512
513audioHapticPlayerInstance.on('endOfStream', endOfStreamCallback);
514
515audioHapticPlayerInstance.off('endOfStream', endOfStreamCallback);
516```
517
518### on('audioInterrupt')
519
520on(type: 'audioInterrupt', callback: Callback<audio.InterruptEvent>): void
521
522Subscribes to the audio interruption event, which is triggered when the audio focus is changed. This API uses an asynchronous callback to return the result.
523
524**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
525
526**Parameters**
527
528| Name  | Type                    | Mandatory| Description                                                                      |
529| -------- | ----------------------- | ---- | -------------------------------------------------------------------------- |
530| type     | string                  | Yes  | Event type. The value is fixed at **'audioInterrupt'**.                    |
531| callback | Callback<[audio.InterruptEvent](js-apis-audio.md#interruptevent9)> | Yes  | Callback used to return the audio interruption event received by the application when playback is interrupted.|
532
533**Example**
534
535```ts
536import { audio } from '@kit.AudioKit';
537
538let isPlaying: boolean; // An identifier specifying whether rendering is in progress.
539let isDucked: boolean; // An identifier specifying whether the audio volume is reduced.
540
541audioHapticPlayerInstance.on('audioInterrupt', (interruptEvent: audio.InterruptEvent) => {
542  // When an audio interruption event occurs, the audioHapticPlayerInstance receives the interruptEvent callback and performs processing based on the content in the callback.
543  // 1. (Optional) The audioHapticPlayerInstance reads the value of interruptEvent.forceType to see whether the system has forcibly performed the operation.
544  // Note: In the default focus policy, INTERRUPT_HINT_RESUME maps to the force type INTERRUPT_SHARE, and others map to INTERRUPT_FORCE. Therefore, the value of forceType does not need to be checked.
545  // 2. (Mandatory) The audioHapticPlayerInstance then reads the value of interruptEvent.hintType and performs corresponding processing.
546  if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) {
547    // The audio focus event has been forcibly executed by the system. The application needs to update its status and displayed content.
548    switch (interruptEvent.hintType) {
549      case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
550        // The audio stream has been paused and temporarily loses the focus. It will receive the interruptEvent corresponding to resume when it is able to regain the focus.
551        console.info('Force paused. Update playing status and stop writing');
552        isPlaying = false; // A simplified processing indicating several operations for switching the application to the paused state.
553        break;
554      case audio.InterruptHint.INTERRUPT_HINT_STOP:
555        // The audio stream has been stopped and permanently loses the focus. The user must manually trigger the operation to resume rendering.
556        console.info('Force stopped. Update playing status and stop writing');
557        isPlaying = false; // A simplified processing indicating several operations for switching the application to the paused state.
558        break;
559      case audio.InterruptHint.INTERRUPT_HINT_DUCK:
560        // The audio stream is rendered at a reduced volume.
561        console.info('Force ducked. Update volume status');
562        isDucked = true; // A simplified processing indicating several operations for updating the volume status.
563        break;
564      case audio.InterruptHint.INTERRUPT_HINT_UNDUCK:
565        // The audio stream is rendered at the normal volume.
566        console.info('Force ducked. Update volume status');
567        isDucked = false; // A simplified processing indicating several operations for updating the volume status.
568        break;
569      default:
570        break;
571    }
572  } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) {
573    // The audio focus event needs to be operated by the application, which can choose the processing mode. It is recommended that the application process the event according to the value of InterruptHint.
574    switch (interruptEvent.hintType) {
575      case audio.InterruptHint.INTERRUPT_HINT_RESUME:
576        // It is recommended that the application continue rendering. (The audio stream has been forcibly paused and temporarily lost the focus. It can resume rendering now.)
577        // The INTERRUPT_HINT_RESUME operation must be proactively executed by the application and cannot be forcibly executed by the system. Therefore, the INTERRUPT_HINT_RESUME event must map to INTERRUPT_SHARE.
578        console.info('Resume force paused renderer or ignore');
579        // To continue rendering, the application must perform the required operations.
580        break;
581      default:
582        break;
583    }
584  }
585});
586```
587
588### off('audioInterrupt')
589
590off(type: 'audioInterrupt', callback?: Callback<audio.InterruptEvent>): void
591
592Unsubscribes from the audio interruption event. This API uses an asynchronous callback to return the result.
593
594**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
595
596**Parameters**
597
598| Name| Type  | Mandatory| Description                                             |
599| ----- | ----- | ---- | ------------------------------------------------- |
600| type   | string | Yes  | Event type. The value is fixed at **'audioInterrupt'**.|
601| callback | Callback<[audio.InterruptEvent](js-apis-audio.md#interruptevent9)> | No  | Callback used to return the audio interruption event when the subscription is canceled.|
602
603**Example**
604
605```ts
606import { audio } from '@kit.AudioKit';
607
608// Cancel all subscriptions to the event.
609audioHapticPlayerInstance.off('audioInterrupt');
610
611// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter.
612let isPlaying: boolean; // An identifier specifying whether rendering is in progress.
613let isDucked: boolean; // An identifier specifying whether the audio volume is reduced.
614let audioInterruptCallback = (interruptEvent: audio.InterruptEvent) => {
615  // When an audio interruption event occurs, the audioHapticPlayerInstance receives the interruptEvent callback and performs processing based on the content in the callback.
616  // 1. (Optional) The audioHapticPlayerInstance reads the value of interruptEvent.forceType to see whether the system has forcibly performed the operation.
617  // Note: In the default focus policy, INTERRUPT_HINT_RESUME maps to the force type INTERRUPT_SHARE, and others map to INTERRUPT_FORCE. Therefore, the value of forceType does not need to be checked.
618  // 2. (Mandatory) The audioHapticPlayerInstance then reads the value of interruptEvent.hintType and performs corresponding processing.
619  if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) {
620    // The audio focus event has been forcibly executed by the system. The application needs to update its status and displayed content.
621    switch (interruptEvent.hintType) {
622      case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
623        // The audio stream has been paused and temporarily loses the focus. It will receive the interruptEvent corresponding to resume when it is able to regain the focus.
624        console.info('Force paused. Update playing status and stop writing');
625        isPlaying = false; // A simplified processing indicating several operations for switching the application to the paused state.
626        break;
627      case audio.InterruptHint.INTERRUPT_HINT_STOP:
628        // The audio stream has been stopped and permanently loses the focus. The user must manually trigger the operation to resume rendering.
629        console.info('Force stopped. Update playing status and stop writing');
630        isPlaying = false; // A simplified processing indicating several operations for switching the application to the paused state.
631        break;
632      case audio.InterruptHint.INTERRUPT_HINT_DUCK:
633        // The audio stream is rendered at a reduced volume.
634        console.info('Force ducked. Update volume status');
635        isDucked = true; // A simplified processing indicating several operations for updating the volume status.
636        break;
637      case audio.InterruptHint.INTERRUPT_HINT_UNDUCK:
638        // The audio stream is rendered at the normal volume.
639        console.info('Force ducked. Update volume status');
640        isDucked = false; // A simplified processing indicating several operations for updating the volume status.
641        break;
642      default:
643        break;
644    }
645  } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) {
646    // The audio focus event needs to be operated by the application, which can choose the processing mode. It is recommended that the application process the event according to the value of InterruptHint.
647    switch (interruptEvent.hintType) {
648      case audio.InterruptHint.INTERRUPT_HINT_RESUME:
649        // It is recommended that the application continue rendering. (The audio stream has been forcibly paused and temporarily lost the focus. It can resume rendering now.)
650        // The INTERRUPT_HINT_RESUME operation must be proactively executed by the application and cannot be forcibly executed by the system. Therefore, the INTERRUPT_HINT_RESUME event must map to INTERRUPT_SHARE.
651        console.info('Resume force paused renderer or ignore');
652        // To continue rendering, the application must perform the required operations.
653        break;
654      default:
655        break;
656    }
657  }
658};
659
660audioHapticPlayerInstance.on('audioInterrupt', audioInterruptCallback);
661
662audioHapticPlayerInstance.off('audioInterrupt', audioInterruptCallback);
663```
664