1# Vibrator开发指导 2 3 4## 场景介绍 5 6当设备需要设置不同的振动效果时,可以调用Vibrator模块,例如:设备的按键可以设置不同强度和不同时长的振动,闹钟和来电可以设置不同强度和时长的单次或周期振动。 7 8详细的接口介绍请参考[Vibrator接口](../reference/apis/js-apis-vibrator.md)。 9 10 11## 接口说明 12 13| 模块 | 接口名 | 描述 | 14| ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | 15| ohos.vibrator | startVibration(effect: VibrateEffect, attribute: VibrateAttribute): Promise<void> | 根据指定振动效果和振动属性触发马达振动,使用Promise异步回调。 | 16| ohos.vibrator | startVibration(effect: VibrateEffect, attribute: VibrateAttribute, callback: AsyncCallback<void>): void | 根据指定振动效果和振动属性触发马达振动,使用Callback异步回调。 | 17| ohos.vibrator | stopVibration(stopMode: VibratorStopMode): Promise<void> | 按照指定模式停止马达的振动。 | 18| ohos.vibrator | stopVibration(stopMode: VibratorStopMode, callback: AsyncCallback<void>): void | 按照指定模式停止马达的振动。 | 19| ohos.vibrator | stopVibration(): Promise<void> | 停止所有模式的马达振动。 | 20| ohos.vibrator | stopVibration(callback: AsyncCallback<void>): void | 停止所有模式的马达振动。 | 21| ohos.vibrator | isSupportEffect(effectId: string): Promise<boolean> | 查询是否支持传入的参数effectId。返回true则表示支持,否则不支持 | 22| ohos.vibrator | isSupportEffect(effectId: string, callback: AsyncCallback<boolean>): void | 查询是否支持传入的参数effectId。返回true则表示支持,否则不支持 | 23 24 25## 自定义振动格式 26 27自定义振动提供给用户设计自己所需振动效果的能力,用户可通过自定义振动配置文件,并遵循相应规则编排所需振动形式,使能更加开放的振感交互体验。 28 29自定义振动配置文件为Json格式,在形式上如下所示: 30 31```json 32{ 33 "MetaData": { 34 "Create": "2023-01-09", 35 "Description": "a haptic case", 36 "Version": 1.0, 37 "ChannelNumber": 1 38 }, 39 "Channels": [ 40 { 41 "Parameters": { 42 "Index": 1 43 }, 44 "Pattern": [ 45 { 46 "Event": { 47 "Type": "transient", 48 "StartTime": 0, 49 "Parameters": { 50 "Intensity": 100, 51 "Frequency": 31 52 } 53 } 54 }, 55 { 56 "Event": { 57 "Type": "continuous", 58 "StartTime": 100, 59 "Duration": 54, 60 "Parameters": { 61 "Intensity": 38, 62 "Frequency": 30 63 } 64 } 65 } 66 ] 67 } 68 ] 69} 70``` 71 72Json文件共包含2个属性。 73- "MetaData"属性中为文件头信息,可在如下属性中添加描述。<br> 74"Version":必填项,文件格式的版本号,向前兼容,目前起步仅支持版本1.0;<br> 75"ChannelNumber":必填项,表示马达振动的通道数,目前仅支持单通道,规定为1;<br> 76"Create":可选项,可记录文件创作时间;<br> 77"Description":可选项,可指明振动效果、创建信息等附加说明。<br> 78- "Channels"属性中为马达振动通道的相关信息。<br> 79 80"Channels"是Json数组,表示各个通道的信息,包含2个属性。 81- "Parameters"属性中为通道参数。<br> 82"Index":必填项,表示通道编号,单通道下规定为1。<br> 83- "Pattern"属性中为马达振动序列。<br> 84 85"Pattern"是Json数组,每个"Event"属性代表1个振动事件,支持添加2种振动类型。 86- 类型1:"transient"类型,瞬态短振动,干脆有力;<br> 87- 类型2:"continuous"类型,稳态长振动,具备长时间输出强劲有力振动的能力。<br> 88 89振动事件参数信息具体如下表: 90 91| 参数 | 说明 | 范围| 92| --- | ------------------------ | ---| 93| Type | 振动事件类型,必填 | "transient" 或"continuous"| 94| StartTime | 振动的起始时间,必填 | 单位ms,有效范围为[0, 1800 000],振动事件不能重叠| 95| Duration | 振动持续时间,仅当类型为"continuous"时有效 | 单位ms,有效范围为(10, 1600)| 96| Intensity | 振动强度,必填 | 有效范围为[0, 100],这里的强度值为相对值,并不代表真实强度| 97| Frequency | 振动频率,必填 | 有效范围为[0, 100],这里的频率值为相对值,并不代表真实频率| 98 99其他要求: 100 101| 参数 | 要求 | 102| -------- | ------------------------ | 103| 振动事件(event)的数量 | 不得超过128个 | 104| 振动配置文件长度 | 不得超过64KB | 105 106 107## 开发步骤 108 1091. 控制设备上的振动器,需要申请权限ohos.permission.VIBRATE。具体配置方式请参考[权限申请声明](../security/accesstoken-guidelines.md)。 110 1112. 根据指定振动效果和振动属性触发马达振动。 112 113```ts 114import vibrator from '@ohos.vibrator'; 115import { BusinessError } from '@ohos.base'; 116 117try { 118 // 使用startVibration需要添加ohos.permission.VIBRATE权限 119 vibrator.startVibration({ 120 type: 'time', 121 duration: 1000, 122 }, { 123 id: 0, 124 usage: 'alarm' 125 }, (error: BusinessError) => { 126 if (error) { 127 console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); 128 return; 129 } 130 console.info('Succeed in starting vibration.'); 131 }); 132} catch (err) { 133 let e: BusinessError = err as BusinessError; 134 console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); 135} 136``` 137 1383. 按照指定模式停止马达的振动。 139 140```ts 141import vibrator from '@ohos.vibrator'; 142import { BusinessError } from '@ohos.base'; 143 144try { 145 // 按照VIBRATOR_STOP_MODE_TIME模式停止振动, 使用stopVibration需要添加ohos.permission.VIBRATE权限 146 vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME, (error: BusinessError) => { 147 if (error) { 148 console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); 149 return; 150 } 151 console.info('Succeeded in stopping vibration.'); 152 }) 153} catch (err) { 154 let e: BusinessError = err as BusinessError; 155 console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); 156} 157``` 158 1594. 停止所有模式的马达振动。 160 161```ts 162import vibrator from '@ohos.vibrator'; 163import { BusinessError } from '@ohos.base'; 164 165try { 166 vibrator.startVibration({ 167 type: 'time', 168 duration: 1000, 169 }, { 170 id: 0, 171 usage: 'alarm' 172 }, (error: BusinessError) => { 173 if (error) { 174 console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); 175 return; 176 } 177 console.info('Succeed in starting vibration'); 178 }); 179 // 停止所有类型的马达振动 180 vibrator.stopVibration((error: BusinessError) => { 181 if (error) { 182 console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); 183 return; 184 } 185 console.info('Succeed in stopping vibration'); 186 }) 187} catch (error) { 188 let e: BusinessError = error as BusinessError; 189 console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); 190} 191``` 192 1935. 查询是否支持传入的参数effectId。 194 195```ts 196import vibrator from '@ohos.vibrator'; 197import { BusinessError } from '@ohos.base'; 198 199try { 200 // 查询是否支持'haptic.clock.timer' 201 vibrator.isSupportEffect('haptic.clock.timer', (err: BusinessError, state: boolean) => { 202 if (err) { 203 console.error(`Failed to query effect. Code: ${err.code}, message: ${err.message}`); 204 return; 205 } 206 console.info('Succeed in querying effect'); 207 if (state) { 208 try { 209 // 使用startVibration需要添加ohos.permission.VIBRATE权限 210 vibrator.startVibration({ 211 type: 'preset', 212 effectId: 'haptic.clock.timer', 213 count: 1, 214 }, { 215 usage: 'unknown' 216 }, (error: BusinessError) => { 217 if (error) { 218 console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); 219 } else { 220 console.info('Succeed in starting vibration'); 221 } 222 }); 223 } catch (error) { 224 let e: BusinessError = error as BusinessError; 225 console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); 226 } 227 } 228 }) 229} catch (error) { 230 let e: BusinessError = error as BusinessError; 231 console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); 232} 233``` 234 2356. 启动和停止自定义振动 236 237```ts 238import vibrator from '@ohos.vibrator'; 239import { BusinessError } from '@ohos.base'; 240import resourceManager from '@ohos.resourceManager'; 241 242// 获取振动文件资源描述符 243async function getRawfileFd(fileName: string): Promise<resourceManager.RawFileDescriptor> { 244 let rawFd = await getContext().resourceManager.getRawFd(fileName); 245 return rawFd; 246} 247 248// 关闭振动文件资源描述符 249async function closeRawfileFd(fileName: string): Promise<void> { 250 await getContext().resourceManager.closeRawFd(fileName) 251} 252 253// 播放自定义振动,使用startVibration、stopVibration需要添加ohos.permission.VIBRATE权限 254async function playCustomHaptic(fileName: string): Promise<void> { 255 try { 256 let rawFd = await getRawfileFd(fileName); 257 vibrator.startVibration({ 258 type: "file", 259 hapticFd: { fd: rawFd.fd, offset: rawFd.offset, length: rawFd.length } 260 }, { 261 usage: "alarm" 262 }).then(() => { 263 console.info('Succeed in starting vibration'); 264 }, (error: BusinessError) => { 265 console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); 266 }); 267 vibrator.stopVibration((error: BusinessError) => { 268 if (error) { 269 console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); 270 return; 271 } 272 console.info('Succeed in stopping vibration'); 273 }) 274 await closeRawfileFd(fileName); 275 } catch (error) { 276 let e: BusinessError = error as BusinessError; 277 console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); 278 } 279} 280``` 281 282 283## 相关实例 284 285针对振动开发,有以下相关实例可供参考: 286 287- [振动(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-4.0-Release/code/BasicFeature/DeviceManagement/Vibrator/BasicVibration) 288 289- [自定义振动(ArkTS)(Full SDK)(API10)](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-4.0-Release/code/BasicFeature/DeviceManagement/Vibrator/CustomHaptic) 290