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文件共包含2个属性。 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 // 获取文件资源描述符 236 let rawFd: resourceManager.RawFileDescriptor = getContext().resourceManager.getRawFdSync(fileName); 237 238 // 触发马达振动 239 try { 240 vibrator.startVibration({ 241 type: "file", 242 hapticFd: { fd: rawFd.fd, offset: rawFd.offset, length: rawFd.length } 243 }, { 244 id: 0, 245 usage: 'alarm' 246 }, (error: BusinessError) => { 247 if (error) { 248 console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); 249 return; 250 } 251 console.info('Succeed in starting vibration'); 252 }); 253 } catch (err) { 254 let e: BusinessError = err as BusinessError; 255 console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); 256 } 257 258 // 关闭文件资源描述符 259 getContext().resourceManager.closeRawFdSync(fileName); 260 ``` 261 2623. 停止马达的振动。 263 264 方式一,按照指定模式停止对应的马达振动,自定义振动不支持此类停止方式: 265 266 停止固定时长振动: 267 268 ```ts 269 import { vibrator } from '@kit.SensorServiceKit'; 270 import { BusinessError } from '@kit.BasicServicesKit'; 271 272 try { 273 // 按照VIBRATOR_STOP_MODE_TIME模式停止振动 274 vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME, (error: BusinessError) => { 275 if (error) { 276 console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); 277 return; 278 } 279 console.info('Succeed in stopping vibration'); 280 }) 281 } catch (err) { 282 let e: BusinessError = err as BusinessError; 283 console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); 284 } 285 ``` 286 287 停止预置振动: 288 289 ```ts 290 import { vibrator } from '@kit.SensorServiceKit'; 291 import { BusinessError } from '@kit.BasicServicesKit'; 292 293 try { 294 // 按照VIBRATOR_STOP_MODE_PRESET模式停止振动 295 vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, (error: BusinessError) => { 296 if (error) { 297 console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); 298 return; 299 } 300 console.info('Succeed in stopping vibration'); 301 }) 302 } catch (err) { 303 let e: BusinessError = err as BusinessError; 304 console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); 305 } 306 ``` 307 308 方式二,停止所有模式的马达振动,包括自定义振动: 309 310 ```ts 311 import { vibrator } from '@kit.SensorServiceKit'; 312 import { BusinessError } from '@kit.BasicServicesKit'; 313 314 try { 315 // 停止所有模式的马达振动 316 vibrator.stopVibration((error: BusinessError) => { 317 if (error) { 318 console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); 319 return; 320 } 321 console.info('Succeed in stopping vibration'); 322 }) 323 } catch (error) { 324 let e: BusinessError = error as BusinessError; 325 console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); 326 } 327 ``` 328 329 330## 相关实例 331 332针对振动开发,有以下相关实例可供参考: 333 334- [振动(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DeviceManagement/Vibrator/BasicVibration) 335 336- [自定义振动(ArkTS)(Full SDK)(API10)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DeviceManagement/Vibrator/CustomHaptic) 337