1# Vibrator Development 2 3 4## When to Use 5 6You can set different vibration effects as needed, for example, customizing the vibration intensity, frequency, and duration for button touches, alarm clocks, and incoming calls. 7 8For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md). 9 10 11## Available APIs 12 13| Module | API | Description | 14| ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | 15| ohos.vibrator | startVibration(effect: VibrateEffect, attribute: VibrateAttribute): Promise<void> | Starts vibration with the specified effect and attribute. This API uses a promise to return the result.| 16| ohos.vibrator | startVibration(effect: VibrateEffect, attribute: VibrateAttribute, callback: AsyncCallback<void>): void | Starts vibration with the specified effect and attribute. This API uses an asynchronous callback to return the result.| 17| ohos.vibrator | stopVibration(stopMode: VibratorStopMode): Promise<void> | Stops vibration in the specified mode. This API uses a promise to return the result. | 18| ohos.vibrator | stopVibration(stopMode: VibratorStopMode, callback: AsyncCallback<void>): void | Stops vibration in the specified mode. This API uses an asynchronous callback to return the result. | 19| ohos.vibrator | stopVibration(): Promise<void> | Stops vibration in all modes. This API uses a promise to return the result. | 20| ohos.vibrator | stopVibration(callback: AsyncCallback<void>): void | Stops vibration in all modes. This API uses an asynchronous callback to return the result. | 21| ohos.vibrator | isSupportEffect(effectId: string): Promise<boolean> | Checks whether the passed effect ID is supported. This API uses a promise to return the result. The value **true** means that the passed effect ID is supported, and **false** means the opposite.| 22| ohos.vibrator | isSupportEffect(effectId: string, callback: AsyncCallback<boolean>): void | Checks whether the passed effect ID is supported. This API uses an asynchronous callback to return the result. The value **true** means that the passed effect ID is supported, and **false** means the opposite.| 23 24 25## Custom Vibration Format 26 27Custom vibration enables you to design desired vibration effects by customizing a vibration configuration file and orchestrating vibration forms based on the corresponding rules. 28 29The custom vibration configuration file is in JSON format. An example file is as follows: 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 72This JSON file contains two attributes: **MetaData** and **Channels**. 73- **MetaData** contains information about the file header. You can add the following attributes under **MetaData**: 74 - **Version**: version number of the file format, which is forward compatible. Currently, only version 1.0 is supported. This parameter is mandatory. 75 - **ChannelNumber**: number of channels for vibration. Currently, only one channel is supported, and the value is fixed at **1**. This parameter is mandatory. 76 - **Create**: time when the file was created. This parameter is optional. 77 - **Description**: additional information such as the vibration effect and creation information. This parameter is optional. 78- **Channels** provides information about the vibration channel. It is a JSON array that holds information about each channel. It contains two attributes: **Parameters** and **Pattern**. 79 - **Parameters** provides parameters related to the channel. Under it, **Index** indicates the channel ID. The value is fixed at **1** for a single channel. This parameter is mandatory. 80 - **Pattern** indicates the vibration sequence. It is a JSON array. Under it, **Event** indicates a vibration event, which can be either of the following types: 81 - **transient**: short vibration 82 - **continuous**: long vibration 83 84The table below describes the parameters under **Event**. 85 86| Parameter| Description| Value or Value Range| 87| --- | ------------------------ | ---| 88| Type | Type of the vibration event. This parameter is mandatory.| **transient** or **continuous**| 89| StartTime | Start time of the vibration. This parameter is mandatory.| [0, 1800 000], in ms, without overlapping| 90| Duration | Duration of the vibration. This parameter is valid only when **Type** is **continuous**.| (10, 1600), in ms| 91| Intensity | Intensity of the vibration. This parameter is mandatory.| [0, 100], a relative value that does not represent the actual vibration strength.| 92| Frequency | Frequency of the vibration. This parameter is mandatory.| [0, 100], a relative value that does not represent the actual vibration frequency.| 93 94The following requirements must be met: 95 96| Item| Description | 97| -------- | ------------------------ | 98| Number of vibration events| No more than 128| 99| Length of the vibration configuration file| Not greater than 64 KB| 100 101 102## How to Develop 103 1041. Before using the vibrator on a device, you must declare the **ohos.permission.VIBRATE** permission. For details about how to configure a permission, see [Declaring Permissions](../security/accesstoken-guidelines.md). 105 1062. Start vibration with the specified effect and attribute. 107 108```ts 109import vibrator from '@ohos.vibrator'; 110import { BusinessError } from '@ohos.base'; 111 112try { 113 // To use startVibration, you must configure the ohos.permission.VIBRATE permission. 114 vibrator.startVibration({ 115 type: 'time', 116 duration: 1000, 117 }, { 118 id: 0, 119 usage: 'alarm' 120 }, (error: BusinessError) => { 121 if (error) { 122 console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); 123 return; 124 } 125 console.info('Succeed in starting vibration.'); 126 }); 127} catch (err) { 128 let e: BusinessError = err as BusinessError; 129 console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); 130} 131``` 132 1333. Stop vibration in the specified mode. 134 135```ts 136import vibrator from '@ohos.vibrator'; 137import { BusinessError } from '@ohos.base'; 138 139try { 140 // Stop vibration in VIBRATOR_STOP_MODE_TIME mode. To use stopVibration, you must configure the ohos.permission.VIBRATE permission. 141 vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME, (error: BusinessError) => { 142 if (error) { 143 console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); 144 return; 145 } 146 console.info('Succeeded in stopping vibration.'); 147 }) 148} catch (err) { 149 let e: BusinessError = err as BusinessError; 150 console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); 151} 152``` 153 1544. Stop vibration in all modes. 155 156```ts 157import vibrator from '@ohos.vibrator'; 158import { BusinessError } from '@ohos.base'; 159 160try { 161 vibrator.startVibration({ 162 type: 'time', 163 duration: 1000, 164 }, { 165 id: 0, 166 usage: 'alarm' 167 }, (error: BusinessError) => { 168 if (error) { 169 console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); 170 return; 171 } 172 console.info('Succeed in starting vibration'); 173 }); 174 // Stop vibration in all modes. 175 vibrator.stopVibration((error: BusinessError) => { 176 if (error) { 177 console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); 178 return; 179 } 180 console.info('Succeed in stopping vibration'); 181 }) 182} catch (error) { 183 let e: BusinessError = error as BusinessError; 184 console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); 185} 186``` 187 1885. Check whether the passed effect ID is supported. 189 190```ts 191import vibrator from '@ohos.vibrator'; 192import { BusinessError } from '@ohos.base'; 193 194try { 195 // Check whether 'haptic.clock.timer' is supported. 196 vibrator.isSupportEffect('haptic.clock.timer', (err: BusinessError, state: boolean) => { 197 if (err) { 198 console.error(`Failed to query effect. Code: ${err.code}, message: ${err.message}`); 199 return; 200 } 201 console.info('Succeed in querying effect'); 202 if (state) { 203 try { 204 // To use startVibration, you must configure the ohos.permission.VIBRATE permission. 205 vibrator.startVibration({ 206 type: 'preset', 207 effectId: 'haptic.clock.timer', 208 count: 1, 209 }, { 210 usage: 'unknown' 211 }, (error: BusinessError) => { 212 if (error) { 213 console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); 214 } else { 215 console.info('Succeed in starting vibration'); 216 } 217 }); 218 } catch (error) { 219 let e: BusinessError = error as BusinessError; 220 console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); 221 } 222 } 223 }) 224} catch (error) { 225 let e: BusinessError = error as BusinessError; 226 console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); 227} 228``` 229 2306. Start and stop custom vibration. 231 232```ts 233import vibrator from '@ohos.vibrator'; 234import { BusinessError } from '@ohos.base'; 235import resourceManager from '@ohos.resourceManager'; 236 237// Obtain the file descriptor of the vibration configuration file. 238async function getRawfileFd(fileName: string): Promise<resourceManager.RawFileDescriptor> { 239 let rawFd = await getContext().resourceManager.getRawFd(fileName); 240 return rawFd; 241} 242 243// Close the file descriptor of the vibration configuration file. 244async function closeRawfileFd(fileName: string): Promise<void> { 245 await getContext().resourceManager.closeRawFd(fileName) 246} 247 248// Play the custom vibration. To use startVibration and stopVibration, you must configure the ohos.permission.VIBRATE permission. 249async function playCustomHaptic(fileName: string): Promise<void> { 250 try { 251 let rawFd = await getRawfileFd(fileName); 252 vibrator.startVibration({ 253 type: "file", 254 hapticFd: { fd: rawFd.fd, offset: rawFd.offset, length: rawFd.length } 255 }, { 256 usage: "alarm" 257 }).then(() => { 258 console.info('Succeed in starting vibration'); 259 }, (error: BusinessError) => { 260 console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); 261 }); 262 vibrator.stopVibration((error: BusinessError) => { 263 if (error) { 264 console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); 265 return; 266 } 267 console.info('Succeed in stopping vibration'); 268 }) 269 await closeRawfileFd(fileName); 270 } catch (error) { 271 let e: BusinessError = error as BusinessError; 272 console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); 273 } 274} 275``` 276 277