• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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## AudioHapticFileDescriptor<sup>20+</sup>
58
59Describes the audio-haptic file descriptor.
60
61>**NOTE**
62>
63> Ensure that **fd** is an available file descriptor and the values of **offset** and **length** are correct.
64
65**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
66
67| Name    | Type          |Read-Only | Optional | Description                            |
68| --------- | -------------- | ---- | ---- | --------------------------------- |
69| fd        | number         | No  | No  | File descriptor of the audio-haptic file, which is generally greater than or equal to 0.|
70| offset    | number         | No  | Yes  | Offset in the file from which data will be read. By default, the offset is 0.|
71| length    | number         | No  | Yes  | Number of bytes to read. By default, the length is the number of bytes remaining in the file from the offset position.|
72
73## AudioHapticManager
74
75Manages the audio-haptic feature. Before calling any API in AudioHapticManager, you must use [getAudioHapticManager](#audiohapticgetaudiohapticmanager) to create an AudioHapticManager instance.
76
77### registerSource
78
79registerSource(audioUri: string, hapticUri: string): Promise&lt;number&gt;
80
81Registers an audio-haptic source. This API uses a promise to return the result.
82
83**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
84
85**Parameters**
86
87| Name  | Type                                     | Mandatory| Description                    |
88| -------- | ---------------------------------------- | ---- | ------------------------ |
89| 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/arkts-apis-media-AVPlayer.md). 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.          |
90| 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.        |
91
92**Return value**
93
94| Type               | Description                           |
95| ------------------- | ------------------------------- |
96| Promise&lt;number&gt; | Promise used to return the source ID.|
97
98**Error codes**
99
100For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
101
102| ID| Error Message                             |
103| ------- |-----------------------------------|
104| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
105
106**Example**
107
108```ts
109import { BusinessError } from '@kit.BasicServicesKit';
110
111let audioUri = 'data/audioTest.wav'; // Change it to the URI of the target audio source.
112let hapticUri = 'data/hapticTest.json'; // Change it to the URI of the target haptic source.
113let id = 0;
114
115audioHapticManagerInstance.registerSource(audioUri, hapticUri).then((value: number) => {
116  console.info(`Promise returned to indicate that the source id of the registerd source ${value}.`);
117  id = value;
118}).catch ((err: BusinessError) => {
119  console.error(`Failed to register source ${err}`);
120});
121```
122
123### registerSourceFromFd<sup>20+</sup>
124
125registerSourceFromFd(audioFd: AudioHapticFileDescriptor, hapticFd: AudioHapticFileDescriptor): Promise&lt;number&gt;
126
127Registers audio-haptic resources through a file descriptor to ensure they are synchronized during playback. This API uses a promise to return the result.
128
129**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
130
131**Parameters**
132
133| Name | Type                                    | Mandatory| Description                   |
134| -------- | ---------------------------------------- | ---- | ------------------------ |
135| audioFd | [AudioHapticFileDescriptor](#audiohapticfiledescriptor20) | Yes| Valid file descriptor object that has been opened, used to describe the audio file. The offset and length must match the actual file length.|
136| hapticFd | [AudioHapticFileDescriptor](#audiohapticfiledescriptor20) | Yes| Valid file descriptor object that has been opened, used to describe the haptic file. The offset and length must match the actual file length.|
137
138**Return value**
139
140| Type              | Description                          |
141| ------------------- | ------------------------------- |
142| Promise&lt;number&gt; | Promise used to return the ID of the resource registered.|
143
144**Example**
145
146```ts
147import { BusinessError } from '@kit.BasicServicesKit';
148import { common } from '@kit.AbilityKit';
149
150const context = getContext(this) as common.UIAbilityContext;
151
152const audioFile = await context.resourceManager.getRawFd('audioTest.ogg'); // Use the corresponding file in the rawfile directory.
153const audioFd: audioHaptic.AudioHapticFileDescriptor = {
154  fd: audioFile.fd,
155  offset: audioFile.offset,
156  length: audioFile.length,
157};
158
159const hapticFile = await context.resourceManager.getRawFd('hapticTest.json'); // Use the corresponding file in the rawfile directory.
160const hapticFd: audioHaptic.AudioHapticFileDescriptor = {
161  fd: hapticFile.fd,
162  offset: hapticFile.offset,
163  length: hapticFile.length,
164};
165let id = 0;
166
167audioHapticManagerInstance.registerSourceFromFd(audioFd, hapticFd).then((value: number) => {
168  console.info(`Promise returned with registered source id ${value}.`);
169  id = value;
170}).catch ((err: BusinessError) => {
171  console.error(`Failed to register source ${err}`);
172});
173```
174
175### unregisterSource
176
177unregisterSource(id: number): Promise&lt;void&gt;
178
179Unregisters an audio-haptic source. This API uses a promise to return the result.
180
181**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
182
183**Parameters**
184
185| Name  | Type                                     | Mandatory| Description                    |
186| -------- | ---------------------------------------- | ---- | ------------------------ |
187| id       | number                                   | Yes  | Source ID.   |
188
189**Return value**
190
191| Type                 | Description                        |
192| --------------------- | --------------------------- |
193| Promise&lt;void&gt;   | Promise that returns no value.|
194
195**Error codes**
196
197For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
198
199| ID| Error Message                             |
200| ------- |-----------------------------------|
201| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
202
203**Example**
204
205```ts
206import { BusinessError } from '@kit.BasicServicesKit';
207
208let audioUri = 'data/audioTest.wav'; // Change it to the URI of the target audio source.
209let hapticUri = 'data/hapticTest.json'; // Change it to the URI of the target haptic source.
210let id = 0;
211
212audioHapticManagerInstance.registerSource(audioUri, hapticUri).then((value: number) => {
213  console.info(`Promise returned to indicate that the source id of the registerd source ${value}.`);
214  id = value;
215}).catch ((err: BusinessError) => {
216  console.error(`Failed to register source ${err}`);
217});
218
219audioHapticManagerInstance.unregisterSource(id).then(() => {
220  console.info(`Promise returned to indicate that unregister source successfully`);
221}).catch ((err: BusinessError) => {
222  console.error(`Failed to unregistere source ${err}`);
223});
224```
225
226### setAudioLatencyMode
227
228setAudioLatencyMode(id:number, latencyMode: AudioLatencyMode): void
229
230Sets the latency mode for an audio-haptic source.
231
232**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
233
234**Parameters**
235
236| Name  | Type                                     | Mandatory| Description                    |
237| -------- | ---------------------------------------- | ---- | ------------------------ |
238| id          | number                                | Yes  | Source ID.   |
239| latencyMode | [AudioLatencyMode](#audiolatencymode) | Yes  | Audio latency mode.            |
240
241**Error codes**
242
243For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Media Error Codes](../apis-media-kit/errorcode-media.md).
244
245| ID| Error Message                             |
246| ------- |-----------------------------------|
247| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
248| 5400102 | Operation not allowed.            |
249
250**Example**
251
252```ts
253import { BusinessError } from '@kit.BasicServicesKit';
254
255let audioUri = 'data/audioTest.wav'; // Change it to the URI of the target audio source.
256let hapticUri = 'data/hapticTest.json'; // Change it to the URI of the target haptic source.
257let id = 0;
258
259audioHapticManagerInstance.registerSource(audioUri, hapticUri).then((value: number) => {
260  console.info(`Promise returned to indicate that the source id of the registerd source ${value}.`);
261  id = value;
262}).catch ((err: BusinessError) => {
263  console.error(`Failed to register source ${err}`);
264});
265
266let latencyMode: audioHaptic.AudioLatencyMode = audioHaptic.AudioLatencyMode.AUDIO_LATENCY_MODE_FAST;
267
268audioHapticManagerInstance.setAudioLatencyMode(id, latencyMode);
269```
270
271### setStreamUsage
272
273setStreamUsage(id: number, usage: audio.StreamUsage): void
274
275Sets the stream usage for an audio-haptic source.
276
277**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
278
279**Parameters**
280
281| Name  | Type                                     | Mandatory| Description                    |
282| -------- | ---------------------------------------- | ---- | ------------------------ |
283| id       | number                                   | Yes  | Source ID.   |
284| usage    | [audio.StreamUsage](arkts-apis-audio-e.md#streamusage) | Yes  | Stream usage.   |
285
286**Error codes**
287
288For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Media Error Codes](../apis-media-kit/errorcode-media.md).
289
290| ID| Error Message                             |
291| ------- |-----------------------------------|
292| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3.Parameter verification failed. |
293| 5400102 | Operation not allowed.            |
294
295**Example**
296
297```ts
298import { audio } from '@kit.AudioKit';
299import { BusinessError } from '@kit.BasicServicesKit';
300
301let audioUri = 'data/audioTest.wav'; // Change it to the URI of the target audio source.
302let hapticUri = 'data/hapticTest.json'; // Change it to the URI of the target haptic source.
303let id = 0;
304
305audioHapticManagerInstance.registerSource(audioUri, hapticUri).then((value: number) => {
306  console.info(`Promise returned to indicate that the source id of the registerd source ${value}.`);
307  id = value;
308}).catch ((err: BusinessError) => {
309  console.error(`Failed to register source ${err}`);
310});
311
312let usage: audio.StreamUsage = audio.StreamUsage.STREAM_USAGE_NOTIFICATION;
313
314audioHapticManagerInstance.setStreamUsage(id, usage);
315```
316
317### createPlayer
318
319createPlayer(id: number, options?: AudioHapticPlayerOptions): Promise&lt;AudioHapticPlayer&gt;
320
321Creates an audio-haptic player. This API uses a promise to return the result.
322
323**Required permissions**: ohos.permission.VIBRATE
324
325If the audio-haptic player needs to trigger vibration, check whether the application has the permission.
326
327**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
328
329**Parameters**
330
331| Name  | Type                                     | Mandatory| Description                    |
332| -------- | ---------------------------------------- | ---- | ------------------------ |
333| id       | number                                   | Yes  | Source ID.   |
334| options  | [AudioHapticPlayerOptions](#audiohapticplayeroptions) | No  | Options of the audio-haptic player.|
335
336**Return value**
337
338| Type               | Description                           |
339| ------------------- | ------------------------------- |
340| Promise&lt;[AudioHapticPlayer](#audiohapticplayer)&gt; |Promise used to return the audio-haptic player.|
341
342**Error codes**
343
344For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Media Error Codes](../apis-media-kit/errorcode-media.md).
345
346| ID| Error Message                             |
347| ------- |-----------------------------------|
348| 201 | Permission denied. |
349| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
350| 5400102 | Operation not allowed. |
351| 5400103 | I/O error. |
352| 5400106 | Unsupport format. |
353
354**Example**
355
356```ts
357import { BusinessError } from '@kit.BasicServicesKit';
358
359let audioUri = 'data/audioTest.wav'; // Change it to the URI of the target audio source.
360let hapticUri = 'data/hapticTest.json'; // Change it to the URI of the target haptic source.
361let id = 0;
362
363audioHapticManagerInstance.registerSource(audioUri, hapticUri).then((value: number) => {
364  console.info(`Promise returned to indicate that the source id of the registerd source ${value}.`);
365  id = value;
366}).catch ((err: BusinessError) => {
367  console.error(`Failed to register source ${err}`);
368});
369
370let options: audioHaptic.AudioHapticPlayerOptions = {muteAudio: false, muteHaptics: false};
371let audioHapticPlayerInstance: audioHaptic.AudioHapticPlayer | undefined = undefined;
372
373audioHapticManagerInstance.createPlayer(id, options).then((value: audioHaptic.AudioHapticPlayer) => {
374  audioHapticPlayerInstance = value;
375  console.info(`Create the audio haptic player successfully.`);
376}).catch ((err: BusinessError) => {
377  console.error(`Failed to create the audio haptic player. ${err}`);
378});
379```
380
381## AudioHapticType
382
383Enumerates the audio haptic types.
384
385**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
386
387| Name                           |  Value    | Description                                        |
388| ------------------------------- | ------ | -------------------------------------------- |
389| AUDIO_HAPTIC_TYPE_AUDIO         | 0      | Audio.                                   |
390| AUDIO_HAPTIC_TYPE_HAPTIC        | 1      | Haptic.                                   |
391
392## AudioHapticPlayer
393
394Implements audio-haptic playback. Before calling any API in AudioHapticPlayer, you must use [createPlayer](#createplayer) to create an AudioHapticPlayer instance.
395
396### isMuted
397
398isMuted(type: AudioHapticType): boolean
399
400Checks whether an audio-haptic type is muted.
401
402**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
403
404**Parameters**
405
406| Name  | Type                                     | Mandatory| Description                    |
407| -------- | ---------------------------------------- | ---- | ------------------------ |
408| type     | [AudioHapticType](#audiohaptictype)      | Yes  | Audio-haptic type.               |
409
410**Return value**
411
412| Type               | Description                           |
413| ------------------- | ------------------------------- |
414| boolean             | Check result. The value **true** means that the audio-haptic type is muted, and **false** means the opposite.|
415
416**Error codes**
417
418For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
419
420| ID| Error Message                             |
421| ------- |-----------------------------------|
422| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Parameter verification failed. |
423
424**Example**
425
426```ts
427let audioHapticType: audioHaptic.AudioHapticType = audioHaptic.AudioHapticType.AUDIO_HAPTIC_TYPE_AUDIO;
428
429let result: boolean = audioHapticPlayerInstance.isMuted(audioHapticType);
430```
431
432### start
433
434start(): Promise&lt;void&gt;
435
436Starts playback. This API uses a promise to return the result.
437
438**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
439
440**Return value**
441
442| Type                 | Description                        |
443| --------------------- | --------------------------- |
444| Promise&lt;void&gt;   | Promise that returns no value.|
445
446**Error codes**
447
448For details about the error codes, see [Media Error Codes](../apis-media-kit/errorcode-media.md).
449
450| ID  | Error Message                             |
451|---------|-----------------------------------|
452| 5400102 | Operate not permit. |
453| 5400103 | IO error. |
454| 5400105 | Service died. |
455
456**Example**
457
458```ts
459import { BusinessError } from '@kit.BasicServicesKit';
460
461audioHapticPlayerInstance.start().then(() => {
462  console.info(`Promise returned to indicate that start playing successfully.`);
463}).catch ((err: BusinessError) => {
464  console.error(`Failed to start playing. ${err}`);
465});
466```
467
468### stop
469
470stop(): Promise&lt;void&gt;
471
472Stops playback. This API uses a promise to return the result.
473
474**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
475
476**Return value**
477
478| Type               | Description                             |
479| ------------------- | -------------------------------- |
480| Promise&lt;void&gt; | Promise that returns no value.|
481
482**Error codes**
483
484For details about the error codes, see [Media Error Codes](../apis-media-kit/errorcode-media.md).
485
486| ID  | Error Message                             |
487|---------|-----------------------------------|
488| 5400102 | Operate not permit. |
489| 5400105 | Service died. |
490
491**Example**
492
493```ts
494import { BusinessError } from '@kit.BasicServicesKit';
495
496audioHapticPlayerInstance.stop().then(() => {
497  console.info(`Promise returned to indicate that stop playing successfully.`);
498}).catch ((err: BusinessError) => {
499  console.error(`Failed to stop playing. ${err}`);
500});
501```
502
503### release
504
505release(): Promise&lt;void&gt;
506
507Releases this audio-haptic player. This API uses a promise to return the result.
508
509**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
510
511**Return value**
512
513| Type               | Description                           |
514| ------------------- | ------------------------------- |
515| Promise&lt;void&gt; | Promise that returns no value.|
516
517**Error codes**
518
519For details about the error codes, see [Media Error Codes](../apis-media-kit/errorcode-media.md).
520
521| ID  | Error Message                             |
522|---------|-----------------------------------|
523| 5400105 | Service died. |
524
525**Example**
526
527```ts
528import { BusinessError } from '@kit.BasicServicesKit';
529
530audioHapticPlayerInstance.release().then(() => {
531  console.info(`Promise returned to indicate that release the audio haptic player successfully.`);
532}).catch ((err: BusinessError) => {
533  console.error(`Failed to release the audio haptic player. ${err}`);
534});
535```
536
537### setVolume<sup>20+</sup>
538
539setVolume(volume: number): Promise&lt;void&gt;
540
541Sets the volume for this audio-haptic player. This API uses a promise to return the result.
542
543>**NOTE**
544>
545> This API must be called before the audio-haptic player is released.
546
547**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
548
549**Parameters**
550
551| Name | Type                                    | Mandatory| Description                   |
552| -------- | ---------------------------------------- | ---- | ------------------------ |
553| volume     | number                                | Yes | Volume, in the range [0.00, 1.00], where 1.00 indicates the maximum volume (100%).|
554
555**Return value**
556
557| Type               | Description                           |
558| ------------------- | ------------------------------- |
559| Promise&lt;void&gt; | Promise that returns no value.|
560
561**Error codes**
562
563For details about the error codes, see [Media Error Codes](../apis-media-kit/errorcode-media.md).
564
565| ID  | Error Message                             |
566|---------|-----------------------------------|
567| 5400105  | Service died. |
568| 5400102  | Operate not permit in current state. |
569| 5400108  | Parameter out of range. |
570
571**Example**
572
573```ts
574import { BusinessError } from '@kit.BasicServicesKit';
575
576audioHapticPlayerInstance.setVolume(0.5).then(() => {
577  console.info('Promise returned to indicate that set volume successfully.');
578}).catch ((err: BusinessError) => {
579  console.error(`Failed to set volume. ${err}`);
580});
581```
582
583### setLoop<sup>20+</sup>
584
585setLoop(loop: boolean): Promise&lt;void&gt;
586
587Sets this audio-haptic player to play in a loop. This API uses a promise to return the result.
588
589>**NOTE**
590>
591> This API must be called before the audio-haptic player is released.
592
593**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
594
595**Parameters**
596
597| Name | Type                                    | Mandatory| Description                   |
598| -------- | ---------------------------------------- | ---- | ------------------------ |
599| loop | boolean                           | Yes | Whether to play in a loop. The value **true** means to play in a loop, and **false** means the opposite.|
600
601**Return value**
602
603| Type               | Description                           |
604| ------------------- | ------------------------------- |
605| Promise&lt;void&gt; | Promise that returns no value.|
606
607**Error codes**
608
609For details about the error codes, see [Media Error Codes](../apis-media-kit/errorcode-media.md).
610
611| ID  | Error Message                             |
612|---------|-----------------------------------|
613| 5400102  | Operate not permit in current state. |
614
615**Example**
616
617```ts
618import { BusinessError } from '@kit.BasicServicesKit';
619
620audioHapticPlayerInstance.setLoop(true).then(() => {
621  console.info('Promise returned to indicate that set player loop successfully.');
622}).catch ((err: BusinessError) => {
623  console.error(`Failed to set player loop. ${err}`);
624});
625```
626
627### on('endOfStream')
628
629on(type: 'endOfStream', callback: Callback&lt;void&gt;): void
630
631Subscribes 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.
632
633**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
634
635**Parameters**
636
637| Name  | Type                    | Mandatory| Description                                                                      |
638| -------- | ----------------------- | ---- | -------------------------------------------------------------------------- |
639| type     | string                  | Yes  | Event type. The event **'endOfStream'** is triggered when the audio stream playback ends.|
640| callback | Callback&lt;void&gt;    | Yes  | Callback that returns no value.|
641
642**Example**
643
644```ts
645audioHapticPlayerInstance.on('endOfStream', () => {
646  console.info(`Receive the callback of endOfStream.`);
647});
648```
649
650### off('endOfStream')
651
652off(type: 'endOfStream', callback?: Callback&lt;void&gt;): void
653
654Unsubscribes from the EOS event. This API uses an asynchronous callback to return the result.
655
656**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
657
658**Parameters**
659
660| Name| Type  | Mandatory| Description                                             |
661| ----- | ----- | ---- | ------------------------------------------------ |
662| type   | string | Yes  | Event type. The event **'endOfStream'** is triggered when the audio stream playback ends.|
663| callback | Callback&lt;void&gt;    | No  | Callback that returns no value.|
664
665**Example**
666
667```ts
668// Cancel all subscriptions to the event.
669audioHapticPlayerInstance.off('endOfStream');
670
671// 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.
672let endOfStreamCallback = () => {
673  console.info(`Receive the callback of endOfStream.`);
674};
675
676audioHapticPlayerInstance.on('endOfStream', endOfStreamCallback);
677
678audioHapticPlayerInstance.off('endOfStream', endOfStreamCallback);
679```
680
681### on('audioInterrupt')
682
683on(type: 'audioInterrupt', callback: Callback&lt;audio.InterruptEvent&gt;): void
684
685Subscribes to the audio interruption event, which is triggered when the audio focus is changed. This API uses an asynchronous callback to return the result.
686
687**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
688
689**Parameters**
690
691| Name  | Type                    | Mandatory| Description                                                                      |
692| -------- | ----------------------- | ---- | -------------------------------------------------------------------------- |
693| type     | string                  | Yes  | Event type. The event **'audioInterrupt'** is triggered when the audio focus is changed.|
694| callback | Callback&lt;[audio.InterruptEvent](arkts-apis-audio-i.md#interruptevent9)&gt; | Yes  | Callback used to return the event information.|
695
696**Example**
697
698```ts
699import { audio } from '@kit.AudioKit';
700
701let isPlaying: boolean; // An identifier specifying whether rendering is in progress.
702let isDucked: boolean; // An identifier specifying whether the audio volume is reduced.
703
704audioHapticPlayerInstance.on('audioInterrupt', (interruptEvent: audio.InterruptEvent) => {
705  // When an audio interruption event occurs, the audioHapticPlayerInstance receives the interruptEvent callback and performs processing based on the content in the callback.
706  // 1. (Optional) The audioHapticPlayerInstance reads the value of interruptEvent.forceType to see whether the system has forcibly performed the operation.
707  // 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.
708  // 2. (Mandatory) The audioHapticPlayerInstance then reads the value of interruptEvent.hintType and performs corresponding processing.
709  if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) {
710    // The audio focus event has been forcibly executed by the system. The application needs to update its status and displayed content.
711    switch (interruptEvent.hintType) {
712      case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
713        // 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.
714        console.info('Force paused. Update playing status and stop writing');
715        isPlaying = false; // A simplified processing indicating several operations for switching the application to the paused state.
716        break;
717      case audio.InterruptHint.INTERRUPT_HINT_STOP:
718        // The audio stream has been stopped and permanently loses the focus. The user must manually trigger the operation to resume rendering.
719        console.info('Force stopped. Update playing status and stop writing');
720        isPlaying = false; // A simplified processing indicating several operations for switching the application to the paused state.
721        break;
722      case audio.InterruptHint.INTERRUPT_HINT_DUCK:
723        // The audio stream is rendered at a reduced volume.
724        console.info('Force ducked. Update volume status');
725        isDucked = true; // A simplified processing indicating several operations for updating the volume status.
726        break;
727      case audio.InterruptHint.INTERRUPT_HINT_UNDUCK:
728        // The audio stream is rendered at the normal volume.
729        console.info('Force ducked. Update volume status');
730        isDucked = false; // A simplified processing indicating several operations for updating the volume status.
731        break;
732      default:
733        break;
734    }
735  } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) {
736    // 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.
737    switch (interruptEvent.hintType) {
738      case audio.InterruptHint.INTERRUPT_HINT_RESUME:
739        // 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.)
740        // 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.
741        console.info('Resume force paused renderer or ignore');
742        // To continue rendering, the application must perform the required operations.
743        break;
744      default:
745        break;
746    }
747  }
748});
749```
750
751### off('audioInterrupt')
752
753off(type: 'audioInterrupt', callback?: Callback&lt;audio.InterruptEvent&gt;): void
754
755Unsubscribes from the audio interruption event. This API uses an asynchronous callback to return the result.
756
757**System capability**: SystemCapability.Multimedia.AudioHaptic.Core
758
759**Parameters**
760
761| Name| Type  | Mandatory| Description                                             |
762| ----- | ----- | ---- | ------------------------------------------------- |
763| type   | string | Yes  | Event type. The event **'audioInterrupt'** is triggered when the audio focus is changed.|
764| callback | Callback&lt;[audio.InterruptEvent](arkts-apis-audio-i.md#interruptevent9)&gt; | No  | Callback used to return the event information.|
765
766**Example**
767
768```ts
769import { audio } from '@kit.AudioKit';
770
771// Cancel all subscriptions to the event.
772audioHapticPlayerInstance.off('audioInterrupt');
773
774// 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.
775let isPlaying: boolean; // An identifier specifying whether rendering is in progress.
776let isDucked: boolean; // An identifier specifying whether the audio volume is reduced.
777let audioInterruptCallback = (interruptEvent: audio.InterruptEvent) => {
778  // When an audio interruption event occurs, the audioHapticPlayerInstance receives the interruptEvent callback and performs processing based on the content in the callback.
779  // 1. (Optional) The audioHapticPlayerInstance reads the value of interruptEvent.forceType to see whether the system has forcibly performed the operation.
780  // 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.
781  // 2. (Mandatory) The audioHapticPlayerInstance then reads the value of interruptEvent.hintType and performs corresponding processing.
782  if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) {
783    // The audio focus event has been forcibly executed by the system. The application needs to update its status and displayed content.
784    switch (interruptEvent.hintType) {
785      case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
786        // 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.
787        console.info('Force paused. Update playing status and stop writing');
788        isPlaying = false; // A simplified processing indicating several operations for switching the application to the paused state.
789        break;
790      case audio.InterruptHint.INTERRUPT_HINT_STOP:
791        // The audio stream has been stopped and permanently loses the focus. The user must manually trigger the operation to resume rendering.
792        console.info('Force stopped. Update playing status and stop writing');
793        isPlaying = false; // A simplified processing indicating several operations for switching the application to the paused state.
794        break;
795      case audio.InterruptHint.INTERRUPT_HINT_DUCK:
796        // The audio stream is rendered at a reduced volume.
797        console.info('Force ducked. Update volume status');
798        isDucked = true; // A simplified processing indicating several operations for updating the volume status.
799        break;
800      case audio.InterruptHint.INTERRUPT_HINT_UNDUCK:
801        // The audio stream is rendered at the normal volume.
802        console.info('Force ducked. Update volume status');
803        isDucked = false; // A simplified processing indicating several operations for updating the volume status.
804        break;
805      default:
806        break;
807    }
808  } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) {
809    // 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.
810    switch (interruptEvent.hintType) {
811      case audio.InterruptHint.INTERRUPT_HINT_RESUME:
812        // 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.)
813        // 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.
814        console.info('Resume force paused renderer or ignore');
815        // To continue rendering, the application must perform the required operations.
816        break;
817      default:
818        break;
819    }
820  }
821};
822
823audioHapticPlayerInstance.on('audioInterrupt', audioInterruptCallback);
824
825audioHapticPlayerInstance.off('audioInterrupt', audioInterruptCallback);
826```
827
828<!--no_check-->