1# 振动开发指导(ArkTS) 2 3 4## 场景介绍 5 6当设备需要设置不同的振动效果时,可以调用Vibrator模块,例如:设备的按键可以设置不同强度和不同时长的振动,闹钟和来电可以设置不同强度和时长的单次或周期振动。 7 8详细的接口介绍请参考[Vibrator接口](../../reference/apis-sensor-service-kit/js-apis-vibrator.md)。 9 10 11## 接口说明 12 13| 名称 | 描述 | 14| ------------------------------------------------------------ | ------------------------------------------------------------ | 15| startVibration(effect: VibrateEffect, attribute: VibrateAttribute): Promise<void> | 根据指定振动效果和振动属性触发马达振动,使用Promise异步回调。 | 16| startVibration(effect: VibrateEffect, attribute: VibrateAttribute, callback: AsyncCallback<void>): void | 根据指定振动效果和振动属性触发马达振动,使用Callback异步回调。 | 17| stopVibration(stopMode: VibratorStopMode): Promise<void> | 按照指定模式停止马达的振动,使用Promise异步回调。 | 18| stopVibration(stopMode: VibratorStopMode, callback: AsyncCallback<void>): void | 按照指定模式停止马达的振动,使用Callback异步回调。 | 19| stopVibration(): Promise<void> | 停止所有模式的马达振动,使用Promise异步回调。 | 20| stopVibration(callback: AsyncCallback<void>): void | 停止所有模式的马达振动,使用Callback异步回调。 | 21| isSupportEffect(effectId: string): Promise<boolean> | 查询是否支持传入的参数effectId。返回true则表示支持,否则不支持,使用Promise异步回调。 | 22| isSupportEffect(effectId: string, callback: AsyncCallback<boolean>): void | 查询是否支持传入的参数effectId。返回true则表示支持,否则不支持,使用Callback异步回调。 | 23 24 25## 振动效果说明 26 27目前支持三类振动效果,如下所示: 28 29| 名称 | 说明 | 30| ------------ | ------------------------------------------------------------ | 31| 固定时长振动 | 传入一个固定时长,马达按照默认强度和频率触发振动,振动效果描述请参考[VibrateTime](../../reference/apis-sensor-service-kit/js-apis-vibrator.md#vibratetime9)。 | 32| 预置振动 | 系统中的[预置振动效果](../../reference/apis-sensor-service-kit/js-apis-vibrator.md#effectid),这些效果适用于某些固定场景,比如效果"haptic.clock.timer"通常用于用户调整计时器时的振感反馈,振动效果描述请参考[VibratePreset](../../reference/apis-sensor-service-kit/js-apis-vibrator.md#vibratepreset9)。 | 33| 自定义振动 | 自定义振动提供给用户设计自己所需振动效果的能力,用户可通过自定义振动配置文件,并遵循相应规则编排所需振动形式,使能更加开放的振感交互体验,效果描述请参考[VibrateFromFile](../../reference/apis-sensor-service-kit/js-apis-vibrator.md#vibratefromfile10)。 | 34 35自定义振动配置文件为Json格式,在形式上如下所示: 36 37```json 38{ 39 "MetaData": { 40 "Create": "2023-01-09", 41 "Description": "a haptic case", 42 "Version": 1.0, 43 "ChannelNumber": 1 44 }, 45 "Channels": [ 46 { 47 "Parameters": { 48 "Index": 0 49 }, 50 "Pattern": [ 51 { 52 "Event": { 53 "Type": "transient", 54 "StartTime": 0, 55 "Parameters": { 56 "Frequency": 31, 57 "Intensity": 100 58 } 59 } 60 }, 61 { 62 "Event": { 63 "Type": "continuous", 64 "StartTime": 40, 65 "Duration": 54, 66 "Parameters": { 67 "Frequency": 30, 68 "Intensity": 38, 69 "Curve": [ 70 { 71 "Time": 0, 72 "Frequency": 0, 73 "Intensity": 0 74 }, 75 { 76 "Time": 1, 77 "Frequency": 15, 78 "Intensity": 0.5 79 }, 80 { 81 "Time": 40, 82 "Frequency": -8, 83 "Intensity": 1.0 84 }, 85 { 86 "Time": 54, 87 "Frequency": 0, 88 "Intensity": 0 89 } 90 ] 91 } 92 } 93 } 94 ] 95 } 96 ] 97} 98``` 99 100Json文件共包含3个属性。 1011. "MetaData"属性中为文件头信息,可在如下属性中添加描述: 102 103 | 名称 | 必填项 | 说明 | 104 | ------------- | ------ | --------------------------------------------- | 105 | Version | 是 | 文件格式的版本号,向前兼容,目前支持版本1.0。 | 106 | ChannelNumber | 是 | 表示马达振动的通道数,最大支持双马达通道。 | 107 | Create | 否 | 可记录文件创作时间。 | 108 | Description | 否 | 可指明振动效果、创建信息等附加说明。 | 109 1102. "Channels"属性中为马达振动通道的相关信息。 111 112 "Channels"是Json数组,表示各个通道的信息,包含2个属性。 113 114 | 名称 | 必填项 | 说明 | 115 | ---------- | ------ | ------------------------------------------------------------ | 116 | Parameters | 是 | 为通道参数。其中"Index"表示通道编号,0表示全通道发送,1、2分别对应左右马达。 | 117 | Pattern | 否 | 马达振动序列。 | 118 119 "Pattern"是Json数组,包含振动事件序列,每个"Event"属性代表1个振动事件,支持添加2种振动类型。 120 121 | 振动类型 | 说明 | 122 | ---------- | ---------------------------------------------- | 123 | transient | 瞬态短振动,干脆有力。 | 124 | continuous | 稳态长振动,具备长时间输出强劲有力振动的能力。 | 125 126 "Event"表示一个振动事件,包含如下属性: 127 128 | 名称 | 必填项 | 说明 | 129 | --------- | ------ | ------------------------------------------------------------ | 130 | Type | 是 | 振动事件类型,为"transient" 或"continuous"。 | 131 | StartTime | 是 | 振动的起始时间,单位ms,有效范围为[0, 1800,000]。 | 132 | Duration | 是 | 振动持续时间,仅当类型为"continuous"时有效,单位ms,有效范围为[0, 5000]。 | 133 1343. "Parameters"表示振动事件参数设置,必填项,可设置以下属性参数: 135 136 | 名称 | 必填项 | 说明 | 137 | --------- | ------ | ------------------------------------------------------------ | 138 | Intensity | 是 | 振动事件强度,有效范围为[0, 100]。 | 139 | Frequency | 是 | 振动事件频率,有效范围为[0, 100]。 | 140 | Curve | 否 | 振动曲线,当振动事件类型为"continuous"时有效,为Json数组,支持设置一组调节点,调节点数量最大支持16个,最小为4个,每个调节点需包含如下属性:<br/>"Time":相对事件起始时间的偏移,最小为0,最大不能超过事件振动时长;<br/>"Intensity":相对事件振动强度的增益,范围为[0, 1],此值乘上振动事件强度为对应时间点调节后的强度;<br/>"Frequency":相对事件振动频率的变化,范围为[-100, 100],此值加上振动事件频率为对应时间点调节后的频率。 | 141 142其他要求: 143 144| 参数 | 要求 | 145| -------- | ------------------------ | 146| 振动事件(event)的数量 | 不得超过128个。 | 147| 振动配置文件长度 | 不得超过64KB。 | 148 149 150## 开发步骤 151 1521. 控制设备上的振动器,需要申请权限ohos.permission.VIBRATE。具体配置方式请参考[声明权限](../../security/AccessToken/declare-permissions.md)。 153 1542. 根据指定振动效果和振动属性触发马达振动。 155 156 **情形一** 按照指定持续时间触发马达振动: 157 158 ```ts 159 import { vibrator } from '@kit.SensorServiceKit'; 160 import { BusinessError } from '@kit.BasicServicesKit'; 161 162 try { 163 // 触发马达振动 164 vibrator.startVibration({ 165 type: 'time', 166 duration: 1000, 167 }, { 168 id: 0, 169 usage: 'alarm' 170 }, (error: BusinessError) => { 171 if (error) { 172 console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); 173 return; 174 } 175 console.info('Succeed in starting vibration'); 176 }); 177 } catch (err) { 178 let e: BusinessError = err as BusinessError; 179 console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); 180 } 181 ``` 182 183 **情形二** 按照预置振动效果触发马达振动,可先查询振动效果是否被支持,再调用振动接口: 184 185 ```ts 186 import { vibrator } from '@kit.SensorServiceKit'; 187 import { BusinessError } from '@kit.BasicServicesKit'; 188 189 try { 190 // 查询是否支持'haptic.effect.soft' 191 vibrator.isSupportEffect('haptic.effect.soft', (err: BusinessError, state: boolean) => { 192 if (err) { 193 console.error(`Failed to query effect. Code: ${err.code}, message: ${err.message}`); 194 return; 195 } 196 console.info('Succeed in querying effect'); 197 if (state) { 198 try { 199 // 触发马达振动 200 vibrator.startVibration({ 201 type: 'preset', 202 effectId: 'haptic.effect.soft', 203 count: 1, 204 intensity: 50, 205 }, { 206 usage: 'unknown' 207 }, (error: BusinessError) => { 208 if (error) { 209 console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); 210 } else { 211 console.info('Succeed in starting vibration'); 212 } 213 }); 214 } catch (error) { 215 let e: BusinessError = error as BusinessError; 216 console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); 217 } 218 } 219 }) 220 } catch (error) { 221 let e: BusinessError = error as BusinessError; 222 console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); 223 } 224 ``` 225 226 **情形三** 按照自定义振动配置文件触发马达振动: 227 228 ```ts 229 import { vibrator } from '@kit.SensorServiceKit'; 230 import { resourceManager } from '@kit.LocalizationKit'; 231 import { BusinessError } from '@kit.BasicServicesKit'; 232 233 const fileName: string = 'xxx.json'; 234 235 @Entry 236 @Component 237 struct Index { 238 uiContext = this.getUIContext(); 239 240 build() { 241 Row() { 242 Column() { 243 Button('alarm-file') 244 .onClick(() => { 245 // 获取文件资源描述符 246 let rawFd: resourceManager.RawFileDescriptor | undefined = this.uiContext.getHostContext()?.resourceManager.getRawFdSync(fileName); 247 if (rawFd != undefined) { 248 // 触发马达振动 249 try { 250 vibrator.startVibration({ 251 type: "file", 252 hapticFd: { fd: rawFd.fd, offset: rawFd.offset, length: rawFd.length } 253 }, { 254 id: 0, 255 usage: 'alarm' // 根据实际选择类型归属不同的开关管控 256 }, (error: BusinessError) => { 257 if (error) { 258 console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); 259 return; 260 } 261 console.info('Succeed in starting vibration'); 262 }); 263 } catch (err) { 264 let e: BusinessError = err as BusinessError; 265 console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); 266 } 267 } 268 // 关闭文件资源描述符 269 this.uiContext.getHostContext()?.resourceManager.closeRawFdSync(fileName); 270 }) 271 } 272 .width('100%') 273 } 274 .height('100%') 275 } 276 } 277 ``` 278 2793. 停止马达的振动。 280 281 **方式一** 按照指定模式停止对应的马达振动,自定义振动不支持此类停止方式: 282 283 停止固定时长振动: 284 285 ```ts 286 import { vibrator } from '@kit.SensorServiceKit'; 287 import { BusinessError } from '@kit.BasicServicesKit'; 288 289 try { 290 // 按照VIBRATOR_STOP_MODE_TIME模式停止振动 291 vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME, (error: BusinessError) => { 292 if (error) { 293 console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); 294 return; 295 } 296 console.info('Succeed in stopping vibration'); 297 }) 298 } catch (err) { 299 let e: BusinessError = err as BusinessError; 300 console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); 301 } 302 ``` 303 304 停止预置振动: 305 306 ```ts 307 import { vibrator } from '@kit.SensorServiceKit'; 308 import { BusinessError } from '@kit.BasicServicesKit'; 309 310 try { 311 // 按照VIBRATOR_STOP_MODE_PRESET模式停止振动 312 vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, (error: BusinessError) => { 313 if (error) { 314 console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); 315 return; 316 } 317 console.info('Succeed in stopping vibration'); 318 }) 319 } catch (err) { 320 let e: BusinessError = err as BusinessError; 321 console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); 322 } 323 ``` 324 325 **方式二** 停止所有模式的马达振动,包括自定义振动: 326 327 ```ts 328 import { vibrator } from '@kit.SensorServiceKit'; 329 import { BusinessError } from '@kit.BasicServicesKit'; 330 331 try { 332 // 停止所有模式的马达振动 333 vibrator.stopVibration((error: BusinessError) => { 334 if (error) { 335 console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); 336 return; 337 } 338 console.info('Succeed in stopping vibration'); 339 }) 340 } catch (error) { 341 let e: BusinessError = error as BusinessError; 342 console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); 343 } 344 ``` 345 346 347## 相关实例 348 349针对振动开发,有以下相关实例可供参考: 350 351- [振动(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DeviceManagement/Vibrator/BasicVibration) 352 353- [自定义振动(ArkTS)(Full SDK)(API10)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DeviceManagement/Vibrator/CustomHaptic) 354