1# @ohos.multimedia.audioHaptic (音振协同) 2<!--Kit: Audio Kit--> 3<!--Subsystem: Multimedia--> 4<!--Owner: @songshenke--> 5<!--Designer: @caixuejiang; @hao-liangfei; @zhanganxiang--> 6<!--Tester: @Filger--> 7<!--Adviser: @zengyawen--> 8 9音振协同,表示在播放声音时,可同步发起振动。可用于来电通知、消息提醒等场景。 10 11> **说明:** 12> 13> 本模块首批接口从API version 11开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 14> 15 16## 导入模块 17 18```ts 19import { audioHaptic } from '@kit.AudioKit'; 20``` 21 22## audioHaptic.getAudioHapticManager 23 24getAudioHapticManager(): AudioHapticManager 25 26获取音振管理器。 27 28**系统能力:** SystemCapability.Multimedia.AudioHaptic.Core 29 30**返回值:** 31 32| 类型 | 说明 | 33| ----------------------------- | ------------ | 34| [AudioHapticManager](#audiohapticmanager) | 音振管理器。 | 35 36**示例:** 37```ts 38let audioHapticManagerInstance: audioHaptic.AudioHapticManager = audioHaptic.getAudioHapticManager(); 39``` 40 41## AudioLatencyMode 42 43枚举,音频时延模式。 44 45**系统能力:** SystemCapability.Multimedia.AudioHaptic.Core 46 47| 名称 | 值 | 说明 | 48| ------------------------------- | ------ | -------------------------------------------- | 49| AUDIO_LATENCY_MODE_NORMAL | 0 | 普通时延模式。 | 50| AUDIO_LATENCY_MODE_FAST | 1 | 低时延模式。该模式适用于比较短的音频文件,音频文件过长时可能被截断,该特性与[SoundPool](../apis-media-kit/js-apis-inner-multimedia-soundPool.md#soundpool)一致。 | 51 52## AudioHapticPlayerOptions 53 54音振播放器选项。 55 56**系统能力:** SystemCapability.Multimedia.AudioHaptic.Core 57 58| 名称 | 类型 |只读 | 可选 | 说明 | 59| --------- | -------------- | ---- |---| --------------------------------- | 60| muteAudio | boolean | 否 | 是 | 是否将音频静音,true表示将音频静音,false表示正常播放声音。若不填该参数,则默认为false。 | 61| muteHaptics | boolean | 否 | 是 | 是否禁止振动,true表示将禁止振动,false表示正常振动。若不填该参数,则默认为false。 | 62 63## AudioHapticFileDescriptor<sup>20+</sup> 64 65描述音振文件描述符。 66 67>**注意:** 68> 69> 开发者需要确保fd是可用的文件描述符,且offset和length的值都是正确的。 70 71**系统能力:**: SystemCapability.Multimedia.AudioHaptic.Core 72 73| 名称 | 类型 |只读 | 可选 | 说明 | 74| --------- | -------------- | ---- | ---- | --------------------------------- | 75| fd | number | 否 | 否 | 音振资源文件的文件描述符,通常大于等于0。| 76| offset | number | 否 | 是 | 文件中数据读取的偏移量。默认情况下,偏移量为0。| 77| length | number | 否 | 是 | 读取数据的字节长度。默认情况下,长度为文件中从偏移量位置开始的剩余字节数。| 78 79## AudioHapticManager 80 81管理音振协同功能。在调用AudioHapticManager的接口前,需要先通过[getAudioHapticManager](#audiohapticgetaudiohapticmanager)创建实例。 82 83### registerSource 84 85registerSource(audioUri: string, hapticUri: string): Promise<number> 86 87注册音频和振动资源的Uri。使用Promise异步回调。 88 89**系统能力:** SystemCapability.Multimedia.AudioHaptic.Core 90 91**参数:** 92 93| 参数名 | 类型 | 必填 | 说明 | 94| -------- | ---------------------------------------- | ---- | ------------------------ | 95| audioUri | string | 是 | 音频资源的Uri。对普通时延模式,音频资源格式和路径格式的支持可参考[media.AVPlayer](../apis-media-kit/arkts-apis-media-AVPlayer.md);对低时延模式,音频资源格式支持可参考[SoundPool](../apis-media-kit/js-apis-inner-multimedia-soundPool.md#soundpool),路径格式需满足[文件管理模块open函数](../apis-core-file-kit/js-apis-file-fs.md#fsopen)的要求。对两种时延模式,均建议传入文件的绝对路径。 | 96| hapticUri | string | 是 | 振动资源的Uri。振动资源格式支持可参考[vibrator](../apis-sensor-service-kit/js-apis-vibrator.md#hapticfiledescriptor10),路径格式需满足[文件管理模块open函数](../apis-core-file-kit/js-apis-file-fs.md#fsopen)的要求。建议传入文件的绝对路径。 | 97 98**返回值:** 99 100| 类型 | 说明 | 101| ------------------- | ------------------------------- | 102| Promise<number> | Promise对象,返回注册资源的source id。 | 103 104**错误码:** 105 106以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。 107 108| 错误码ID | 错误信息 | 109| ------- |-----------------------------------| 110| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 111 112**示例:** 113 114```ts 115import { BusinessError } from '@kit.BasicServicesKit'; 116 117let audioUri = 'data/audioTest.wav'; // 需更改为目标音频资源的Uri。 118let hapticUri = 'data/hapticTest.json'; // 需更改为目标振动资源的Uri。 119let id = 0; 120 121audioHapticManagerInstance.registerSource(audioUri, hapticUri).then((value: number) => { 122 console.info(`Promise returned to indicate that the source id of the registerd source ${value}.`); 123 id = value; 124}).catch((err: BusinessError) => { 125 console.error(`Failed to register source ${err}`); 126}); 127``` 128 129### registerSourceFromFd<sup>20+</sup> 130 131registerSourceFromFd(audioFd: AudioHapticFileDescriptor, hapticFd: AudioHapticFileDescriptor): Promise<number> 132 133通过文件描述符注册音频和振动资源,确保它们在播放时同步。 134注册资源后,此方法将通过Promise异步返回资源ID。 135 136**系统能力:**: SystemCapability.Multimedia.AudioHaptic.Core 137 138**参数:** 139 140| 参数名 | 类型 | 必填| 说明 | 141| -------- | ---------------------------------------- | ---- | ------------------------ | 142| audioFd | [AudioHapticFileDescriptor](#audiohapticfiledescriptor20) | 是 | 已打开的有效文件描述符对象,用于描述音频文件。配套的offset和length需符合实际文件长度。 | 143| hapticFd | [AudioHapticFileDescriptor](#audiohapticfiledescriptor20) | 是 | 已打开的有效文件描述符对象,用于描述振动文件。配套的offset和length必须符合实际文件长度。 | 144 145**返回值:** 146 147| 类型 | 说明 | 148| ------------------- | ------------------------------- | 149| Promise<number> | 返回注册资源的资源ID。| 150 151**示例:** 152 153```ts 154import { BusinessError } from '@kit.BasicServicesKit'; 155import { common } from '@kit.AbilityKit'; 156 157// 请在组件内获取context,确保this.getUIContext().getHostContext()返回结果为UIAbilityContext。 158let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 159 160let audioFile = context.resourceManager.getRawFdSync('audioTest.ogg'); // 需要改成rawfile目录下的对应文件。 161let audioFd: audioHaptic.AudioHapticFileDescriptor = { 162 fd: audioFile.fd, 163 offset: audioFile.offset, 164 length: audioFile.length, 165}; 166 167let hapticFile = context.resourceManager.getRawFdSync('hapticTest.json'); // 需要改成rawfile目录下的对应文件。 168let hapticFd: audioHaptic.AudioHapticFileDescriptor = { 169 fd: hapticFile.fd, 170 offset: hapticFile.offset, 171 length: hapticFile.length, 172}; 173let id = 0; 174 175audioHapticManagerInstance.registerSourceFromFd(audioFd, hapticFd).then((value: number) => { 176 console.info('Succeeded in doing registerSourceFromFd.'); 177 id = value; 178}).catch((err: BusinessError) => { 179 console.error(`Failed to registerSourceFromFd. Code: ${err.code}, message: ${err.message}`); 180}); 181``` 182 183### unregisterSource 184 185unregisterSource(id: number): Promise<void> 186 187取消注册音频和振动资源。使用Promise异步回调。 188 189**系统能力:** SystemCapability.Multimedia.AudioHaptic.Core 190 191**参数:** 192 193| 参数名 | 类型 | 必填 | 说明 | 194| -------- | ---------------------------------------- | ---- | ------------------------ | 195| id | number | 是 | 已注册资源的source id。 | 196 197**返回值:** 198 199| 类型 | 说明 | 200| --------------------- | --------------------------- | 201| Promise<void> | Promise对象。无返回结果的Promise对象。 | 202 203**错误码:** 204 205以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。 206 207| 错误码ID | 错误信息 | 208| ------- |-----------------------------------| 209| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 210 211**示例:** 212 213```ts 214import { BusinessError } from '@kit.BasicServicesKit'; 215 216let id = 0; // 需要通过registerSource方法获取。 217 218audioHapticManagerInstance.unregisterSource(id).then(() => { 219 console.info('Succeeded in doing unregisterSource.'); 220}).catch((err: BusinessError) => { 221 console.error(`Failed to unregisterSource. Code: ${err.code}, message: ${err.message}`); 222}); 223``` 224 225### setAudioLatencyMode 226 227setAudioLatencyMode(id:number, latencyMode: AudioLatencyMode): void 228 229设置音频时延模式。 230 231**系统能力:** SystemCapability.Multimedia.AudioHaptic.Core 232 233**参数:** 234 235| 参数名 | 类型 | 必填 | 说明 | 236| -------- | ---------------------------------------- | ---- | ------------------------ | 237| id | number | 是 | 已注册资源的source id。 | 238| latencyMode | [AudioLatencyMode](#audiolatencymode) | 是 | 音频时延模式。 | 239 240**错误码:** 241 242以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[媒体服务错误码](../apis-media-kit/errorcode-media.md)。 243 244| 错误码ID | 错误信息 | 245| ------- |-----------------------------------| 246| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 247| 5400102 | Operation not allowed. | 248 249**示例:** 250 251```ts 252import { BusinessError } from '@kit.BasicServicesKit'; 253 254let id = 0; // 需要通过registerSource方法获取。 255 256let latencyMode: audioHaptic.AudioLatencyMode = audioHaptic.AudioLatencyMode.AUDIO_LATENCY_MODE_FAST; 257 258audioHapticManagerInstance.setAudioLatencyMode(id, latencyMode); 259``` 260 261### setStreamUsage 262 263setStreamUsage(id: number, usage: audio.StreamUsage): void 264 265设置音频流使用类型。 266 267**系统能力:** SystemCapability.Multimedia.AudioHaptic.Core 268 269**参数:** 270 271| 参数名 | 类型 | 必填 | 说明 | 272| -------- | ---------------------------------------- | ---- | ------------------------ | 273| id | number | 是 | 已注册资源的source id。 | 274| usage | [audio.StreamUsage](arkts-apis-audio-e.md#streamusage) | 是 | 音频流使用类型。 | 275 276**错误码:** 277 278以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[媒体服务错误码](../apis-media-kit/errorcode-media.md)。 279 280| 错误码ID | 错误信息 | 281| ------- |-----------------------------------| 282| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3.Parameter verification failed. | 283| 5400102 | Operation not allowed. | 284 285**示例:** 286 287```ts 288import { audio } from '@kit.AudioKit'; 289import { BusinessError } from '@kit.BasicServicesKit'; 290 291let id = 0; // 需要通过registerSource方法获取。 292 293let usage: audio.StreamUsage = audio.StreamUsage.STREAM_USAGE_NOTIFICATION; 294 295audioHapticManagerInstance.setStreamUsage(id, usage); 296``` 297 298### createPlayer 299 300createPlayer(id: number, options?: AudioHapticPlayerOptions): Promise<AudioHapticPlayer> 301 302创建音振播放器。使用Promise异步回调。 303 304**需要权限:** ohos.permission.VIBRATE 305 306如果应用创建的AudioHapticPlayer需要触发振动,则需要校验应用是否拥有该权限。 307 308**系统能力:** SystemCapability.Multimedia.AudioHaptic.Core 309 310**参数:** 311 312| 参数名 | 类型 | 必填 | 说明 | 313| -------- | ---------------------------------------- | ---- | ------------------------ | 314| id | number | 是 | 已注册资源的source id。 | 315| options | [AudioHapticPlayerOptions](#audiohapticplayeroptions) | 否 | 音振播放器选项。 | 316 317**返回值:** 318 319| 类型 | 说明 | 320| ------------------- | ------------------------------- | 321| Promise<[AudioHapticPlayer](#audiohapticplayer)> |Promise对象,返回创建的音振播放器。 | 322 323**错误码:** 324 325以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[媒体服务错误码](../apis-media-kit/errorcode-media.md)。 326 327| 错误码ID | 错误信息 | 328| ------- |-----------------------------------| 329| 201 | Permission denied. | 330| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 331| 5400102 | Operation not allowed. | 332| 5400103 | I/O error. | 333| 5400106 | Unsupport format. | 334 335**示例:** 336 337```ts 338import { BusinessError } from '@kit.BasicServicesKit'; 339 340let id = 0; // 需要通过registerSource方法获取。 341 342let options: audioHaptic.AudioHapticPlayerOptions = {muteAudio: false, muteHaptics: false}; 343let audioHapticPlayerInstance: audioHaptic.AudioHapticPlayer | undefined = undefined; 344 345audioHapticManagerInstance.createPlayer(id, options).then((value: audioHaptic.AudioHapticPlayer) => { 346 audioHapticPlayerInstance = value; 347 console.info('Succeeded in doing createPlayer.'); 348}).catch((err: BusinessError) => { 349 console.error(`Failed to createPlayer. Code: ${err.code}, message: ${err.message}`); 350}); 351``` 352 353## AudioHapticType 354 355枚举,音振类型。 356 357**系统能力:** SystemCapability.Multimedia.AudioHaptic.Core 358 359| 名称 | 值 | 说明 | 360| ------------------------------- | ------ | -------------------------------------------- | 361| AUDIO_HAPTIC_TYPE_AUDIO | 0 | 音频。 | 362| AUDIO_HAPTIC_TYPE_HAPTIC | 1 | 振动。 | 363 364## AudioHapticPlayer 365 366音振播放器,提供音振协同播放功能。在调用AudioHapticPlayer的接口前,需要先通过[createPlayer](#createplayer)创建实例。 367 368### isMuted 369 370isMuted(type: AudioHapticType): boolean 371 372查询该音振类型是否被静音。 373 374**系统能力:** SystemCapability.Multimedia.AudioHaptic.Core 375 376**参数:** 377 378| 参数名 | 类型 | 必填 | 说明 | 379| -------- | ---------------------------------------- | ---- | ------------------------ | 380| type | [AudioHapticType](#audiohaptictype) | 是 | 音振类型。 | 381 382**返回值:** 383 384| 类型 | 说明 | 385| ------------------- | ------------------------------- | 386| boolean | 表示查询的音振类型是否被静音。true表示静音,false表示非静音。 | 387 388**错误码:** 389 390以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。 391 392| 错误码ID | 错误信息 | 393| ------- |-----------------------------------| 394| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Parameter verification failed. | 395 396**示例:** 397 398```ts 399let audioHapticType: audioHaptic.AudioHapticType = audioHaptic.AudioHapticType.AUDIO_HAPTIC_TYPE_AUDIO; 400 401let result: boolean = audioHapticPlayerInstance.isMuted(audioHapticType); 402``` 403 404### start 405 406start(): Promise<void> 407 408开始播放。使用Promise异步回调。 409 410**系统能力:** SystemCapability.Multimedia.AudioHaptic.Core 411 412**返回值:** 413 414| 类型 | 说明 | 415| --------------------- | --------------------------- | 416| Promise<void> | Promise对象。无返回结果的Promise对象。 | 417 418**错误码:** 419 420以下错误码的详细介绍请参见[媒体服务错误码](../apis-media-kit/errorcode-media.md)。 421 422| 错误码ID | 错误信息 | 423|---------|-----------------------------------| 424| 5400102 | Operate not permit. | 425| 5400103 | IO error. | 426| 5400105 | Service died. | 427 428**示例:** 429 430```ts 431import { BusinessError } from '@kit.BasicServicesKit'; 432 433audioHapticPlayerInstance.start().then(() => { 434 console.info(`Promise returned to indicate that start playing successfully.`); 435}).catch((err: BusinessError) => { 436 console.error(`Failed to start playing. ${err}`); 437}); 438``` 439 440### stop 441 442stop(): Promise<void> 443 444停止播放。使用Promise异步回调。 445 446**系统能力:** SystemCapability.Multimedia.AudioHaptic.Core 447 448**返回值:** 449 450| 类型 | 说明 | 451| ------------------- | -------------------------------- | 452| Promise<void> | Promise对象。无返回结果的Promise对象。 | 453 454**错误码:** 455 456以下错误码的详细介绍请参见[媒体服务错误码](../apis-media-kit/errorcode-media.md)。 457 458| 错误码ID | 错误信息 | 459|---------|-----------------------------------| 460| 5400102 | Operate not permit. | 461| 5400105 | Service died. | 462 463**示例:** 464 465```ts 466import { BusinessError } from '@kit.BasicServicesKit'; 467 468audioHapticPlayerInstance.stop().then(() => { 469 console.info(`Promise returned to indicate that stop playing successfully.`); 470}).catch((err: BusinessError) => { 471 console.error(`Failed to stop playing. ${err}`); 472}); 473``` 474 475### release 476 477release(): Promise<void> 478 479释放音振播放器。使用Promise异步回调。 480 481**系统能力:** SystemCapability.Multimedia.AudioHaptic.Core 482 483**返回值:** 484 485| 类型 | 说明 | 486| ------------------- | ------------------------------- | 487| Promise<void> | Promise对象。无返回结果的Promise对象。 | 488 489**错误码:** 490 491以下错误码的详细介绍请参见[媒体服务错误码](../apis-media-kit/errorcode-media.md)。 492 493| 错误码ID | 错误信息 | 494|---------|-----------------------------------| 495| 5400105 | Service died. | 496 497**示例:** 498 499```ts 500import { BusinessError } from '@kit.BasicServicesKit'; 501 502audioHapticPlayerInstance.release().then(() => { 503 console.info(`Promise returned to indicate that release the audio haptic player successfully.`); 504}).catch((err: BusinessError) => { 505 console.error(`Failed to release the audio haptic player. ${err}`); 506}); 507``` 508 509### setVolume<sup>20+</sup> 510 511setVolume(volume: number): Promise<void> 512 513设置音振播放器的音量。使用Promise异步回调。 514 515>**注意:** 516> 517> 该方法需在音振播放器释放前调用。 518 519**系统能力:** SystemCapability.Multimedia.AudioHaptic.Core 520 521**参数** 522 523| 参数名 | 类型 | 必填| 说明 | 524| -------- | ---------------------------------------- | ---- | ------------------------ | 525| volume | number | 是 | 取值范围为[0.00, 1.00],其中1.00表示最大音量(100%)。| 526 527**返回值:** 528 529| 类型 | 说明 | 530| ------------------- | ------------------------------- | 531| Promise<void> | Promise对象,无返回结果。 | 532 533**错误码:** 534 535以下错误码的详细介绍请参见[媒体服务错误码](../apis-media-kit/errorcode-media.md)。 536 537| 错误码ID | 错误信息 | 538|---------|-----------------------------------| 539| 5400105 | Service died. | 540| 5400102 | Operate not permit in current state. | 541| 5400108 | Parameter out of range. | 542 543**示例:** 544 545```ts 546import { BusinessError } from '@kit.BasicServicesKit'; 547 548audioHapticPlayerInstance.setVolume(0.5).then(() => { 549 console.info('Promise returned to indicate that set volume successfully.'); 550}).catch((err: BusinessError) => { 551 console.error(`Failed to set volume. ${err}`); 552}); 553``` 554 555### setLoop<sup>20+</sup> 556 557setLoop(loop: boolean): Promise<void> 558 559设置音振播放器循环播放。使用Promise异步回调。 560 561>**注意:** 562> 563> 该方法需在音振播放器销毁前调用。 564 565**系统能力:** SystemCapability.Multimedia.AudioHaptic.Core 566 567**参数** 568 569| 参数名 | 类型 | 必填| 说明 | 570| -------- | ---------------------------------------- | ---- | ------------------------ | 571| loop | boolean | 是 | 是否循环播放。true表示循环播放,false表示不循环播放。 | 572 573**返回值:** 574 575| 类型 | 说明 | 576| ------------------- | ------------------------------- | 577| Promise<void> | Promise对象,无返回结果。 | 578 579**错误码:** 580 581以下错误码的详细介绍请参见[媒体服务错误码](../apis-media-kit/errorcode-media.md)。 582 583| 错误码ID | 错误信息 | 584|---------|-----------------------------------| 585| 5400102 | Operate not permit in current state. | 586 587**示例:** 588 589```ts 590import { BusinessError } from '@kit.BasicServicesKit'; 591 592audioHapticPlayerInstance.setLoop(true).then(() => { 593 console.info('Promise returned to indicate that set player loop successfully.'); 594}).catch((err: BusinessError) => { 595 console.error(`Failed to set player loop. ${err}`); 596}); 597``` 598 599### on('endOfStream') 600 601on(type: 'endOfStream', callback: Callback<void>): void 602 603监听流结束事件(音频流播放结束时触发)。使用callback异步回调。 604 605**系统能力:** SystemCapability.Multimedia.AudioHaptic.Core 606 607**参数:** 608 609| 参数名 | 类型 | 必填 | 说明 | 610| -------- | ----------------------- | ---- | -------------------------------------------------------------------------- | 611| type | string | 是 | 事件回调类型,支持的事件为'endOfStream',当音频流播放结束时,触发该事件。 | 612| callback | Callback<void> | 是 | 回调函数,无返回结果。 | 613 614**示例:** 615 616```ts 617audioHapticPlayerInstance.on('endOfStream', () => { 618 console.info(`Receive the callback of endOfStream.`); 619}); 620``` 621 622### off('endOfStream') 623 624off(type: 'endOfStream', callback?: Callback<void>): void 625 626取消监听流结束事件。使用callback异步回调。 627 628**系统能力:** SystemCapability.Multimedia.AudioHaptic.Core 629 630**参数:** 631 632| 参数名 | 类型 | 必填 | 说明 | 633| ----- | ----- | ---- | ------------------------------------------------ | 634| type | string | 是 | 事件回调类型,支持的事件为'endOfStream',当取消监听流结束事件时,触发该事件。 | 635| callback | Callback<void> | 否 | 回调函数,无返回结果。 | 636 637**示例:** 638 639```ts 640// 取消该事件的所有监听。 641audioHapticPlayerInstance.off('endOfStream'); 642 643// 同一监听事件中,on方法和off方法传入callback参数一致,off方法取消对应on方法订阅的监听。 644let endOfStreamCallback = () => { 645 console.info(`Receive the callback of endOfStream.`); 646}; 647 648audioHapticPlayerInstance.on('endOfStream', endOfStreamCallback); 649 650audioHapticPlayerInstance.off('endOfStream', endOfStreamCallback); 651``` 652 653### on('audioInterrupt') 654 655on(type: 'audioInterrupt', callback: Callback<audio.InterruptEvent>): void 656 657监听音频中断事件(当音频焦点发生变化时触发)。使用callback异步回调。 658 659**系统能力:** SystemCapability.Multimedia.AudioHaptic.Core 660 661**参数:** 662 663| 参数名 | 类型 | 必填 | 说明 | 664| -------- | ----------------------- | ---- | -------------------------------------------------------------------------- | 665| type | string | 是 | 事件回调类型,支持的事件为'audioInterrupt',当音频焦点状态发生变化时,触发该事件。 | 666| callback | Callback<[audio.InterruptEvent](arkts-apis-audio-i.md#interruptevent9)> | 是 | 回调函数,返回中断事件信息。 | 667 668**示例:** 669 670```ts 671import { audio } from '@kit.AudioKit'; 672 673let isPlaying: boolean; // 标识符,表示是否正在渲染。 674let isDucked: boolean; // 标识符,表示是否被降低音量。 675 676audioHapticPlayerInstance.on('audioInterrupt', (interruptEvent: audio.InterruptEvent) => { 677 // 在发生音频打断事件时,audioHapticPlayerInstance收到interruptEvent回调,此处根据其内容做相应处理。 678 // 1. 可选:读取interruptEvent.forceType的类型,判断系统是否已强制执行相应操作。 679 // 注意:默认焦点策略下,INTERRUPT_HINT_RESUME为INTERRUPT_SHARE类型,其余hintType均为INTERRUPT_FORCE类型。因此对forceType可不做判断。 680 // 2. 必选:读取interruptEvent.hintType的类型,做出相应的处理。 681 if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { 682 // 音频焦点事件已由系统强制执行,应用需更新自身状态及显示内容等。 683 switch (interruptEvent.hintType) { 684 case audio.InterruptHint.INTERRUPT_HINT_PAUSE: 685 // 音频流已被暂停,临时失去焦点,待可重获焦点时会收到resume对应的interruptEvent。 686 console.info('Force paused. Update playing status and stop writing'); 687 isPlaying = false; // 简化处理,代表应用切换至暂停状态的若干操作。 688 break; 689 case audio.InterruptHint.INTERRUPT_HINT_STOP: 690 // 音频流已被停止,永久失去焦点,若想恢复渲染,需用户主动触发。 691 console.info('Force stopped. Update playing status and stop writing'); 692 isPlaying = false; // 简化处理,代表应用切换至暂停状态的若干操作。 693 break; 694 case audio.InterruptHint.INTERRUPT_HINT_DUCK: 695 // 音频流已被降低音量渲染。 696 console.info('Force ducked. Update volume status'); 697 isDucked = true; // 简化处理,代表应用更新音量状态的若干操作。 698 break; 699 case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: 700 // 音频流已被恢复正常音量渲染。 701 console.info('Force unducked. Update volume status'); 702 isDucked = false; // 简化处理,代表应用更新音量状态的若干操作。 703 break; 704 default: 705 break; 706 } 707 } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { 708 // 音频焦点事件需由应用进行操作,应用可以自主选择如何处理该事件,建议应用遵从InterruptHint提示处理。 709 switch (interruptEvent.hintType) { 710 case audio.InterruptHint.INTERRUPT_HINT_RESUME: 711 // 建议应用继续渲染(说明音频流此前被强制暂停,临时失去焦点,现在可以恢复渲染)。 712 // 由于INTERRUPT_HINT_RESUME操作需要应用主动执行,系统无法强制,故INTERRUPT_HINT_RESUME事件一定为INTERRUPT_SHARE类型。 713 console.info('Resume force paused renderer or ignore'); 714 // 若选择继续渲染,需在此处主动执行开始渲染的若干操作。 715 break; 716 default: 717 break; 718 } 719 } 720}); 721``` 722 723### off('audioInterrupt') 724 725off(type: 'audioInterrupt', callback?: Callback<audio.InterruptEvent>): void 726 727取消监听音频中断事件。使用callback异步回调。 728 729**系统能力:** SystemCapability.Multimedia.AudioHaptic.Core 730 731**参数:** 732 733| 参数名 | 类型 | 必填 | 说明 | 734| ----- | ----- | ---- | ------------------------------------------------- | 735| type | string | 是 | 事件回调类型,支持的事件为'audioInterrupt',当取消监听音频中断事件时,触发该事件。 | 736| callback | Callback<[audio.InterruptEvent](arkts-apis-audio-i.md#interruptevent9)> | 否 | 回调函数,返回中断事件信息。 | 737 738**示例:** 739 740```ts 741import { audio } from '@kit.AudioKit'; 742 743// 取消该事件的所有监听。 744audioHapticPlayerInstance.off('audioInterrupt'); 745 746// 同一监听事件中,on方法和off方法传入callback参数一致,off方法取消对应on方法订阅的监听。 747let isPlaying: boolean; // 标识符,表示是否正在渲染。 748let isDucked: boolean; // 标识符,表示是否被降低音量。 749let audioInterruptCallback = (interruptEvent: audio.InterruptEvent) => { 750 // 在发生音频打断事件时,audioHapticPlayerInstance收到interruptEvent回调,此处根据其内容做相应处理。 751 // 1. 可选:读取interruptEvent.forceType的类型,判断系统是否已强制执行相应操作。 752 // 注意:默认焦点策略下,INTERRUPT_HINT_RESUME为INTERRUPT_SHARE类型,其余hintType均为INTERRUPT_FORCE类型。因此对forceType可不做判断。 753 // 2. 必选:读取interruptEvent.hintType的类型,做出相应的处理。 754 if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { 755 // 音频焦点事件已由系统强制执行,应用需更新自身状态及显示内容等。 756 switch (interruptEvent.hintType) { 757 case audio.InterruptHint.INTERRUPT_HINT_PAUSE: 758 // 音频流已被暂停,临时失去焦点,待可重获焦点时会收到resume对应的interruptEvent。 759 console.info('Force paused. Update playing status and stop writing'); 760 isPlaying = false; // 简化处理,代表应用切换至暂停状态的若干操作。 761 break; 762 case audio.InterruptHint.INTERRUPT_HINT_STOP: 763 // 音频流已被停止,永久失去焦点,若想恢复渲染,需用户主动触发。 764 console.info('Force stopped. Update playing status and stop writing'); 765 isPlaying = false; // 简化处理,代表应用切换至暂停状态的若干操作。 766 break; 767 case audio.InterruptHint.INTERRUPT_HINT_DUCK: 768 // 音频流已被降低音量渲染。 769 console.info('Force ducked. Update volume status'); 770 isDucked = true; // 简化处理,代表应用更新音量状态的若干操作。 771 break; 772 case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: 773 // 音频流已被恢复正常音量渲染。 774 console.info('Force unducked. Update volume status'); 775 isDucked = false; // 简化处理,代表应用更新音量状态的若干操作。 776 break; 777 default: 778 break; 779 } 780 } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { 781 // 音频焦点事件需由应用进行操作,应用可以自主选择如何处理该事件,建议应用遵从InterruptHint提示处理。 782 switch (interruptEvent.hintType) { 783 case audio.InterruptHint.INTERRUPT_HINT_RESUME: 784 // 建议应用继续渲染(说明音频流此前被强制暂停,临时失去焦点,现在可以恢复渲染)。 785 // 由于INTERRUPT_HINT_RESUME操作需要应用主动执行,系统无法强制,故INTERRUPT_HINT_RESUME事件一定为INTERRUPT_SHARE类型。 786 console.info('Resume force paused renderer or ignore'); 787 // 若选择继续渲染,需在此处主动执行开始渲染的若干操作。 788 break; 789 default: 790 break; 791 } 792 } 793}; 794 795audioHapticPlayerInstance.on('audioInterrupt', audioInterruptCallback); 796 797audioHapticPlayerInstance.off('audioInterrupt', audioInterruptCallback); 798``` 799