js-apis-media.md 58.0 KB
Newer Older
1 2 3 4 5 6 7 8
# 媒体服务

媒体子系统为开发者提供一套简单且易于理解的接口,使得开发者能够方便接入系统并使用系统的媒体资源。

媒体子系统包含了音视频相关媒体业务,提供以下常用功能:

- 音频播放([AudioPlayer](#audioplayer)
- 音频录制([AudioRecorder](#audiorecorder)
9
- 视频录制([VideoRecorder](#VideoRecorder<sup>8+</sup>))
10 11

后续将提供以下功能:视频播放、视频录制、DataSource音视频播放、音视频编解码、容器封装解封装、媒体能力查询等功能。
Z
zengyawen 已提交
12

Z
zengyawen 已提交
13
## 导入模块
Z
zengyawen 已提交
14

15
```js
Z
zengyawen 已提交
16 17 18
import media from '@ohos.multimedia.media';
```

19
##  media.createAudioPlayer
Z
zengyawen 已提交
20

21
createAudioPlayer(): [AudioPlayer](#audioplayer)
Z
zengyawen 已提交
22

23
同步方式创建音频播放实例。
Z
zengyawen 已提交
24

25 26


27
**返回值:**
Z
zengyawen 已提交
28

29 30 31
| 类型                        | 说明                                                         |
| --------------------------- | ------------------------------------------------------------ |
| [AudioPlayer](#audioplayer) | 返回AudioPlayer类实例,失败时返回null。可用于音频播放、暂停、停止等操作。 |
Z
zengyawen 已提交
32

33
**示例:**
Z
zengyawen 已提交
34

35 36 37
```js
var audioPlayer = media.createAudioPlayer();
```
Z
zengyawen 已提交
38

39 40 41 42 43 44 45
## media.createAudioPlayerAsync<sup>8+</sup>

createAudioPlayerAsync(callback: AsyncCallback\<[AudioPlayer](#audioplayer)>): void

异步方式创建音频播放实例。通过注册回调函数获取返回值。

**参数:**
Z
zengyawen 已提交
46

47 48 49
| 参数名   | 类型                                       | 必填 | 说明                           |
| -------- | ------------------------------------------ | ---- | ------------------------------ |
| callback | AsyncCallback<[AudioPlayer](#audioplayer)> | 是   | 异步创建音频播放实例回调方法。 |
Z
zengyawen 已提交
50 51 52

**示例:**

53 54 55 56 57 58 59 60 61
```js
media.createAudioPlayerAsync((error, audio) => {
   if (typeof(audio) != 'undefined') {
       audioPlayer = audio;
       console.info('audio createAudioPlayerAsync success');
   } else {
       console.info(`audio createAudioPlayerAsync fail, error:${error.message}`);
   }
});
Z
zengyawen 已提交
62
```
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93

## media.createAudioPlayerAsync<sup>8+</sup>

createAudioPlayerAsync: Promise<[AudioPlayer](#audioplayer)>

异步方式创建音频播放实例。通过Promise获取返回值。

**返回值:**

| 类型                                 | 说明                                |
| ------------------------------------ | ----------------------------------- |
| Promise<[AudioPlayer](#audioplayer)> | 异步创建音频播放实例Promise返回值。 |

**示例:**

```js
function failureCallback(error) {
    console.info(`audio failureCallback, error:${error.message}`);
}
function catchCallback(error) {
    console.info(`audio catchCallback, error:${error.message}`);
}

await media.createAudioPlayerAsync.then((audio) => {
    if (typeof(audio) != 'undefined') {
       audioPlayer = audio;
       console.info('audio createAudioPlayerAsync success');
   } else {
       console.info('audio createAudioPlayerAsync fail');
   }
}, failureCallback).catch(catchCallback);
Z
zengyawen 已提交
94
```
95

Z
zengyawen 已提交
96 97
## media.createAudioRecorder
createAudioRecorder(): AudioRecorder
Z
zengyawen 已提交
98

Z
zengyawen 已提交
99
创建音频录制的实例来控制音频的录制。
Z
zengyawen 已提交
100

Z
zengyawen 已提交
101
**返回值:**
Z
zengyawen 已提交
102

Z
zengyawen 已提交
103 104 105
| 类型                            | 说明                                      |
| ------------------------------- | ----------------------------------------- |
| [AudioRecorder](#audiorecorder) | 返回AudioRecorder类实例,失败时返回null。 |
Z
zengyawen 已提交
106

Z
zengyawen 已提交
107
**示例:**
108

109
```js
B
bird_j 已提交
110
let audiorecorder = media.createAudioRecorder(); 
Z
zengyawen 已提交
111
```
Z
zengyawen 已提交
112

113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
## media.createAudioRecorderAsync<sup>8+</sup>

createAudioRecorderAsync(callback: AsyncCallback\<[AudioRecorder](#audiorecorder)>): void

异步方式创建音频录制实例。通过注册回调函数获取返回值。

**参数:**

| 参数名   | 类型                                           | 必填 | 说明                           |
| -------- | ---------------------------------------------- | ---- | ------------------------------ |
| callback | AsyncCallback<[AudioRecorder](#audiorecorder)> | 是   | 异步创建音频录制实例回调方法。 |

**示例:**

```js
media.createAudioRecorderAsync((error, audio) => {
   if (typeof(audio) != 'undefined') {
       audioRecorder = audio;
       console.info('audio createAudioRecorderAsync success');
   } else {
       console.info(`audio createAudioRecorderAsync fail, error:${error.message}`);
   }
});
```

## media.createAudioRecorderAsync<sup>8+</sup>

createAudioRecorderAsync: Promise<[AudioRecorder](#audiorecorder)>

异步方式创建音频录制实例。通过Promise获取返回值。

**返回值:**

| 类型                                     | 说明                                |
| ---------------------------------------- | ----------------------------------- |
| Promise<[AudioRecorder](#audiorecorder)> | 异步创建音频录制实例Promise返回值。 |

**示例:**

```js
function failureCallback(error) {
    console.info(`audio failureCallback, error:${error.message}`);
}
function catchCallback(error) {
    console.info(`audio catchCallback, error:${error.message}`);
}

await media.createAudioRecorderAsync.then((audio) => {
    if (typeof(audio) != 'undefined') {
       audioRecorder = audio;
       console.info('audio createAudioRecorderAsync success');
   } else {
       console.info('audio createAudioRecorderAsync fail');
   }
}, failureCallback).catch(catchCallback);
```



## media.createVideoRecorderAsync<sup>8+</sup>

createVideoRecorderAsync(callback: AsyncCallback\<[VideoRecorder](#videorecorder8)>): void

异步方式创建视频录制实例。通过注册回调函数获取返回值。

**参数:**

| 参数名   | 类型                                                        | 必填 | 说明                           |
| -------- | ----------------------------------------------------------- | ---- | ------------------------------ |
| callback | AsyncCallback<[VideoRecorder](#videorecorder8)> | 是   | 异步创建视频录制实例回调方法。 |

**示例:**

```js
media.createVideoRecorderAsync((error, video) => {
   if (typeof(video) != 'undefined') {
       videoRecorder = video;
       console.info('video createVideoRecorderAsync success');
   } else {
       console.info(`video createVideoRecorderAsync fail, error:${error.message}`);
   }
});
```

## media.createVideoRecorderAsync<sup>8+</sup>

createVideoRecorderAsync: Promise<[VideoRecorder](#videorecorder8)>

异步方式创建视频录制实例。通过Promise获取返回值。

**返回值:**

| 类型                                                  | 说明                                |
| ----------------------------------------------------- | ----------------------------------- |
| Promise<[VideoRecorder](#videorecorder8)> | 异步创建视频录制实例Promise返回值。 |

**示例:**

```js
function failureCallback(error) {
    console.info(`video failureCallback, error:${error.message}`);
}
function catchCallback(error) {
    console.info(`video catchCallback, error:${error.message}`);
}

await media.createVideoRecorderAsync.then((video) => {
    if (typeof(video) != 'undefined') {
       videoRecorder = video;
       console.info('video createVideoRecorderAsync success');
   } else {
       console.info('video createVideoRecorderAsync fail');
   }
}, failureCallback).catch(catchCallback);
```



231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
## MediaErrorCode<sup>8+</sup>

媒体服务错误类型枚举

| 名称                       | 值   | 说明                                   |
| -------------------------- | ---- | -------------------------------------- |
| MSERR_OK                   | 0    | 表示操作成功。                         |
| MSERR_NO_MEMORY            | 1    | 表示申请内存失败,系统可能无可用内存。 |
| MSERR_OPERATION_NOT_PERMIT | 2    | 表示无权限执行此操作。                 |
| MSERR_INVALID_VAL          | 3    | 表示传入入参无效。                     |
| MSERR_IO                   | 4    | 表示发生IO错误。                       |
| MSERR_TIMEOUT              | 5    | 表示操作超时。                         |
| MSERR_UNKNOWN              | 6    | 表示未知错误。                         |
| MSERR_SERVICE_DIED         | 7    | 表示服务端失效。                       |
| MSERR_INVALID_STATE        | 8    | 表示在当前状态下,不允许执行此操作。   |
| MSERR_UNSUPPORTED          | 9    | 表示在当前版本下,不支持此操作。       |

## MediaType<sup>8+</sup>

媒体类型枚举

| 名称                | 值   | 说明               |
| ------------------- | ---- | ------------------ |
| MEDIA_TYPE_AUD      | 0    | 表示音频。         |
| MEDIA_TYPE_VID      | 1    | 表示视频。         |
| MEDIA_TYPE_SUBTITLE | 2    | 表示字幕:开发中。 |

## CodecMimeType<sup>8+</sup>

Codec MIME类型枚举

| 名称         | 值                | 说明                     |
| ------------ | ----------------- | ------------------------ |
264
| VIDEO_MPEG4  | ”video/mp4v-es“   | 表示视频/mpeg4类型。     |
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
| AUDIO_MPEG   | "audio/mpeg"      | 表示音频/mpeg类型。      |
| AUDIO_AAC    | "audio/mp4a-latm" | 表示音频/mp4a-latm类型。 |
| AUDIO_VORBIS | "audio/vorbis"    | 表示音频/vorbis类型。    |
| AUDIO_FLAC   | "audio/flac"      | 表示音频/flac类型。      |

## MediaDescriptionKey<sup>8+</sup>

媒体信息描述枚举

| 名称                     | 值              | 说明                                                         |
| ------------------------ | --------------- | ------------------------------------------------------------ |
| MD_KEY_TRACK_INDEX       | "track_index"   | 表示轨道序号,其对应键值类型为number。                       |
| MD_KEY_TRACK_TYPE        | "track_type"    | 表示轨道类型,其对应键值类型为number,参考[MediaType](#mediatype8)。 |
| MD_KEY_CODEC_MIME        | "codec_mime"    | 表示codec_mime类型,其对应键值类型为string。                 |
| MD_KEY_DURATION          | "duration"      | 表示媒体时长,其对应键值类型为number,单位为ms。             |
| MD_KEY_BITRATE           | "bitrate"       | 表示比特率,其对应键值类型为number,单位为bps。              |
| MD_KEY_WIDTH             | "width"         | 表示视频宽度,其对应键值类型为number,单位为像素。           |
| MD_KEY_HEIGHT            | "height"        | 表示视频高度,其对应键值类型为number,单位为像素。           |
| MD_KEY_FRAME_RATE        | "frame_rate"    | 表示视频帧率,其对应键值类型为number,单位为100fps。         |
| MD_KEY_AUD_CHANNEL_COUNT | "channel_count" | 表示声道数,其对应键值类型为number。                         |
| MD_KEY_AUD_SAMPLE_RATE   | "sample_rate"   | 表示采样率,其对应键值类型为number,单位为HZ。               |

## BufferingInfoType<sup>8+</sup>

缓存事件类型枚举

| 名称              | 值   | 说明                       |
| ----------------- | ---- | -------------------------- |
| BUFFERING_START   | 1    | 表示开始缓存。             |
| BUFFERING_END     | 2    | 表示结束缓存。             |
| BUFFERING_PERCENT | 3    | 表示缓存百分比。           |
| CACHED_DURATION   | 4    | 表示缓存时长,单位为毫秒。 |

Z
zengyawen 已提交
298
## AudioPlayer
Z
zengyawen 已提交
299

300
音频播放管理类,用于管理和播放音频媒体。在调用AudioPlayer的方法前,需要先通过[createAudioPlayer()](#media.createaudioplayer)[createAudioPlayerAsync()](#media.createaudioplayerasync8)构建一个[AudioPlayer](#audioplayer)实例。
Z
zengyawen 已提交
301

302
音频播放demo可参考:[音频播放开发指导](../../media/audio-playback.md)
Z
zengyawen 已提交
303

304
### 属性<a name=audioplayer_属性></a>
Z
zengyawen 已提交
305

306 307 308 309 310 311 312
| 名称        | 类型                      | 可读 | 可写 | 说明                                                         |
| ----------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ |
| src         | string                    | 是   | 是   | 音频媒体URI,支持当前主流的音频格式(mp4、aac、mp3、ogg)。<br>**支持路径示例**<br>1、本地绝对路径:file:///data/data/ohos.xxx.xxx/files/test.mp4<br>![zh-cn_image_0000001164217678](figures/zh-cn_image_0000001164217678.png)<br>2、http网络播放路径:开发中<br>3、hls网络播放路径:开发中<br>4、fd类型播放:开发中<br>**注意事项**<br>媒体素材需至少赋予读权限后,才可正常播放 |
| loop        | boolean                   | 是   | 是   | 音频循环播放属性,设置为'true'表示循环播放。                 |
| currentTime | number                    | 是   | 否   | 音频的当前播放位置。                                         |
| duration    | number                    | 是   | 否   | 音频时长。                                                   |
| state       | [AudioState](#audiostate) | 是   | 否   | 音频播放的状态。                                             |
Z
zengyawen 已提交
313

314
### play<a name=audioplayer_play></a>
Z
zengyawen 已提交
315

Z
zengyawen 已提交
316
play(): void
Z
zengyawen 已提交
317

318
开始播放音频资源,需在[dataLoad](#on('play' | 'pause' | 'stop' | 'reset' | 'dataload' | 'finish' | 'volumechange'))事件成功触发后,才能调用play方法。
Z
zengyawen 已提交
319

Z
zengyawen 已提交
320
**示例:**
Z
zengyawen 已提交
321

322 323 324
```js
audioPlayer.on('play', () => {    //设置'play'事件回调
    console.log('audio play success');
Z
zengyawen 已提交
325
});
326
audioPlayer.play();
Z
zengyawen 已提交
327
```
Z
zengyawen 已提交
328

329
### pause<a name=audioplayer_pause></a>
Z
zengyawen 已提交
330

Z
zengyawen 已提交
331
pause(): void
Z
zengyawen 已提交
332

Z
zengyawen 已提交
333
暂停播放音频资源。
Z
zengyawen 已提交
334

Z
zengyawen 已提交
335
**示例:**
Z
zengyawen 已提交
336

337 338 339
```js
audioPlayer.on('pause', () => {    //设置'pause'事件回调
    console.log('audio pause success');
Z
zengyawen 已提交
340
});
341
audioPlayer.pause();
Z
zengyawen 已提交
342
```
Z
zengyawen 已提交
343

344
### stop<a name=audioplayer_stop></a>
Z
zengyawen 已提交
345

Z
zengyawen 已提交
346
stop(): void
Z
zengyawen 已提交
347

Z
zengyawen 已提交
348
停止播放音频资源。
Z
zengyawen 已提交
349

Z
zengyawen 已提交
350
**示例:**
Z
zengyawen 已提交
351

352 353 354 355 356
```js
audioPlayer.on('stop', () => {    //设置'stop'事件回调
    console.log('audio stop success');
});
audioPlayer.stop();
Z
zengyawen 已提交
357
```
358 359 360 361 362 363 364 365 366 367 368 369

### reset<sup>7+</sup><a name=audioplayer_reset></a>

reset(): void

切换播放音频资源。

**示例:**

```js
audioPlayer.on('reset', () => {    //设置'reset'事件回调
    console.log('audio reset success');
Z
zengyawen 已提交
370
});
371
audioPlayer.reset();
Z
zengyawen 已提交
372
```
Z
zengyawen 已提交
373

374
### seek<a name=audioplayer_seek></a>
Z
zengyawen 已提交
375

Z
zengyawen 已提交
376
seek(timeMs: number): void
Z
zengyawen 已提交
377

Z
zengyawen 已提交
378
跳转到指定播放位置。
Z
zengyawen 已提交
379

Z
zengyawen 已提交
380
**参数:**
Z
zengyawen 已提交
381

382 383 384
| 参数名 | 类型   | 必填 | 说明                           |
| ------ | ------ | ---- | ------------------------------ |
| timeMs | number | 是   | 指定的跳转时间节点,单位毫秒。 |
Z
zengyawen 已提交
385

Z
zengyawen 已提交
386
**示例:**
Z
zengyawen 已提交
387

388 389 390 391 392 393 394
```js
audioPlayer.on('timeUpdate', (seekDoneTime) => {    //设置'timeUpdate'事件回调
    if (typeof (seekDoneTime) == 'undefined') {
        console.info('audio seek fail');
        return;
    }
    console.log('audio seek success. seekDoneTime: ' + seekDoneTime);
Z
zengyawen 已提交
395
});
396
audioPlayer.seek(30000);    //seek到30000ms的位置
Z
zengyawen 已提交
397
```
Z
zengyawen 已提交
398

399
### setVolume<a name=audioplayer_setvolume></a>
Z
zengyawen 已提交
400

Z
zengyawen 已提交
401
setVolume(vol: number): void
Z
zengyawen 已提交
402

Z
zengyawen 已提交
403
设置音量。
Z
zengyawen 已提交
404

Z
zengyawen 已提交
405
**参数:**
Z
zengyawen 已提交
406

407 408 409
| 参数名 | 类型   | 必填 | 说明                                                         |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| vol    | number | 是   | 指定的相对音量大小,取值范围为[0.00-1.00],1表示最大音量,即100%。 |
Z
zengyawen 已提交
410

Z
zengyawen 已提交
411
**示例:**
Z
zengyawen 已提交
412

413 414 415
```js
audioPlayer.on('volumeChange', () => {    //设置'volumeChange'事件回调
    console.log('audio volumeChange success');
Z
zengyawen 已提交
416
});
417
audioPlayer.setVolume(1);    //设置音量到100%
Z
zengyawen 已提交
418
```
Z
zengyawen 已提交
419

420
### release<a name=audioplayer_release></a>
Z
zengyawen 已提交
421

422
release(): void
Z
zengyawen 已提交
423

424
释放音频资源。
Z
zengyawen 已提交
425

Z
zengyawen 已提交
426
**示例:**
Z
zengyawen 已提交
427

428 429 430
```js
audioPlayer.release();
audioPlayer = undefined;
Z
zengyawen 已提交
431
```
Z
zengyawen 已提交
432

433
### getTrackDescription<sup>8+</sup><a name=audioplayer_gettrackdescription1></a>
Z
zengyawen 已提交
434

435
getTrackDescription(callback: AsyncCallback<Array<[MediaDescription](#mediadescription8)>>): void
Z
zengyawen 已提交
436

437 438 439 440 441 442 443
通过回调方式获取音频轨道信息。

**参数:**

| 参数名   | 类型                                                         | 必填 | 说明                       |
| -------- | ------------------------------------------------------------ | ---- | -------------------------- |
| callback | AsyncCallback<Array<[MediaDescription](#mediadescription8)>> | 是   | 获取音频轨道信息回调方法。 |
Z
zengyawen 已提交
444

Z
zengyawen 已提交
445
**示例:**
Z
zengyawen 已提交
446

447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
```js
function printfDescription(obj) {
    for (let item in obj) {
        let property = obj[item];
        console.info('audio key is ' + item);
        console.info('audio value is ' + property);
    }
}

audioPlayer.getTrackDescription((error, arrlist) => {
    if (typeof (arrlist) != 'undefined') {
        for (let i = 0; i < arrlist.length; i++) {
            printfDescription(arrlist[i]);
        }
    } else {
        console.log(`audio getTrackDescription fail, error:${error.message}`);
    }
});
Z
zengyawen 已提交
465
```
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505

### getTrackDescription<sup>8+</sup><a name=audioplayer_gettrackdescription2></a>

getTrackDescription(): Promise<Array<[MediaDescription](#mediadescription8)>>

通过Promise方式获取音频轨道信息。

**返回值:**

| 类型                                                   | 说明                            |
| ------------------------------------------------------ | ------------------------------- |
| Promise<Array<[MediaDescription](#mediadescription8)>> | 获取音频轨道信息Promise返回值。 |

**示例:**

```js
function printfDescription(obj) {
    for (let item in obj) {
        let property = obj[item];
        console.info('audio key is ' + item);
        console.info('audio value is ' + property);
    }
}
function failureCallback(error) {
    console.info(`audio failureCallback, error:${error.message}`);
}
function catchCallback(error) {
    console.info(`audio catchCallback, error:${error.message}`);
}

await audioPlayer.getTrackDescription.then((arrlist) => {
    if (typeof (arrlist) != 'undefined') {
        arrayDescription = arrlist;
    } else {
        console.log('audio getTrackDescription fail');
    }
}, failureCallback).catch(catchCallback);
for (let i = 0; i < arrayDescription.length; i++) {
    printfDescription(arrayDescription[i]);
}
Z
zengyawen 已提交
506 507
```

508
### on('bufferingUpdate')<sup>8+</sup>
Z
zengyawen 已提交
509

510
on(type: 'bufferingUpdate', callback: (infoType: [BufferingInfoType](#bufferinginfotype8), value: number) => void): void
Z
zengyawen 已提交
511

512
开始订阅音频缓存更新事件。
Z
zengyawen 已提交
513

Z
zengyawen 已提交
514 515
**参数:**

516 517 518 519
| 参数名   | 类型                                                         | 必填 | 说明                                                         |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type     | string                                                       | 是   | 音频缓存事件回调类型,支持的事件:'bufferingUpdate'。        |
| callback | (infoType: [BufferingInfoType](#bufferinginfotype8), value: number) => void | 是   | 音频缓存事件回调方法。<br>[BufferingInfoType](#bufferinginfotype8)为BUFFERING_PERCENT或CACHED_DURATION时,value值有效,否则固定为0。 |
Z
zengyawen 已提交
520 521 522

**示例:**

523 524 525 526 527
```js
audioPlayer.on('bufferingUpdate', (infoType, value) => {
    console.log('audio bufferingInfo type: ' + infoType);
    console.log('audio bufferingInfo value: ' + value);
});
Z
zengyawen 已提交
528
```
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583

 ### on('play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange')

on(type: 'play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange', callback: () => void): void

开始订阅音频播放事件。

**参数:**

| 参数名   | 类型       | 必填 | 说明                                                         |
| -------- | ---------- | ---- | ------------------------------------------------------------ |
| type     | string     | 是   | 播放事件回调类型,支持的事件包括:'play' \| 'pause' \| 'stop' \| 'reset' \| 'dataLoad' \| 'finish' \| 'volumeChange'。<br>- 'play':完成[play()](#audioplayer_play)调用,音频开始播放,触发该事件。<br>- 'pause':完成[pause()](#audioplayer_pause)调用,音频暂停播放,触发该事件。<br>- 'stop':完成[stop()](#audioplayer_stop)调用,音频停止播放,触发该事件。<br>- 'reset':完成[reset()](#audioplayer_reset)调用,播放器重置,触发该事件。<br>- 'dataLoad':完成音频数据加载后触发该事件,即src属性设置完成后触发该事件。<br>- 'finish':完成音频播放后触发该事件。<br>- 'volumeChange':完成[setVolume()](#audioplayer_setvolume)调用,播放音量改变后触发该事件。 |
| callback | () => void | 是   | 播放事件回调方法。                                           |

**示例:**

```js
let audioPlayer = media.createAudioPlayer();  //创建一个音频播放实例
audioPlayer.on('dataLoad', () => {            //设置'dataLoad'事件回调,src属性设置成功后,触发此回调
	console.info('audio set source success');
    audioPlayer.play();                       //开始播放,并触发'play'事件回调
});
audioPlayer.on('play', () => {                //设置'play'事件回调
	console.info('audio play success');
    audioPlayer.seek(30000);                  //调用seek方法,并触发'timeUpdate'事件回调
});
audioPlayer.on('pause', () => {               //设置'pause'事件回调
	console.info('audio pause success');
    audioPlayer.stop();                       //停止播放,并触发'stop'事件回调
});
audioPlayer.on('reset', () => {               //设置'reset'事件回调
	console.info('audio reset success');
    audioPlayer.release();                    //释放播放实例资源
    audioPlayer = undefined;
});
audioPlayer.on('timeUpdate', (seekDoneTime) => {  //设置'timeUpdate'事件回调
	if (typeof(seekDoneTime) == "undefined") {
        console.info('audio seek fail');
        return;
    }
    console.info('audio seek success, and seek time is ' + seekDoneTime);
    audioPlayer.setVolume(0.5);                //设置音量为50%,并触发'volumeChange'事件回调
});
audioPlayer.on('volumeChange', () => {         //设置'volumeChange'事件回调
	console.info('audio volumeChange success');
    audioPlayer.pause();                       //暂停播放,并触发'pause'事件回调
});
audioPlayer.on('finish', () => {               //设置'finish'事件回调
	console.info('audio play finish');
    audioPlayer.stop();                        //停止播放,并触发'stop'事件回调
});
audioPlayer.on('error', (error) => {           //设置'error'事件回调
	console.info(`audio error called, errName is ${error.name}`);
    console.info(`audio error called, errCode is ${error.code}`);
    console.info(`audio error called, errMessage is ${error.message}`);
Z
zengyawen 已提交
584
});
585
audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp4';  //设置src属性,并触发'dataLoad'事件回调
Z
zengyawen 已提交
586 587 588 589 590
```

### on('timeUpdate')

on(type: 'timeUpdate', callback: Callback\<number>): void
Z
zengyawen 已提交
591

592
开始订阅音频播放[seek()](#audioplayer_seek)时间更新事件。
Z
zengyawen 已提交
593

Z
zengyawen 已提交
594 595
**参数:**

596 597 598 599
| 参数名   | 类型              | 必填 | 说明                                                         |
| -------- | ----------------- | ---- | ------------------------------------------------------------ |
| type     | string            | 是   | 播放事件回调类型,支持的事件包括:'timeUpdate'。<br>- 'timeUpdate':[seek()](#audioplayer_seek)调用完成,触发该事件。 |
| callback | Callback\<number> | 是   | 播放事件回调方法。回调方法入参为成功seek的时间。             |
Z
zengyawen 已提交
600 601 602

**示例:**

603 604 605 606 607 608 609
```js
audioPlayer.on('timeUpdate', (seekDoneTime) => {    //设置'timeUpdate'事件回调
    if (typeof (seekDoneTime) == 'undefined') {
        console.info('audio seek fail');
        return;
    }
    console.log('audio seek success. seekDoneTime: ' + seekDoneTime);
Z
zengyawen 已提交
610
});
611
audioPlayer.seek(30000);    //seek到30000ms的位置
Z
zengyawen 已提交
612 613 614 615 616
```

### on('error')

on(type: 'error', callback: ErrorCallback): void
Z
zengyawen 已提交
617

618
开始订阅音频播放错误事件。
Z
zengyawen 已提交
619

Z
zengyawen 已提交
620 621
**参数:**

622 623 624 625
| 参数名   | 类型          | 必填 | 说明                                                         |
| -------- | ------------- | ---- | ------------------------------------------------------------ |
| type     | string        | 是   | 播放错误事件回调类型,支持的事件包括:'error'。<br>- 'error':音频播放中发生错误,触发该事件。 |
| callback | ErrorCallback | 是   | 播放错误事件回调方法。                                       |
Z
zengyawen 已提交
626 627 628

**示例:**

629 630 631 632 633
```js
audioPlayer.on('error', (error) => {      //设置'error'事件回调
	console.info(`audio error called, errName is ${error.name}`);      //打印错误类型名称
    console.info(`audio error called, errCode is ${error.code}`);      //打印错误码
    console.info(`audio error called, errMessage is ${error.message}`);//打印错误类型详细描述
Z
zengyawen 已提交
634
});
635
audioPlayer.setVolume(3);  //设置volume为无效值,触发'error'事件
Z
zengyawen 已提交
636 637 638
```

## AudioState
Z
zengyawen 已提交
639

640 641 642 643 644 645 646 647 648 649 650 651 652
音频播放的状态机。可通过state属性获取当前状态。

| 名称               | 类型   | 描述           |
| ------------------ | ------ | -------------- |
| idle               | string | 音频播放空闲。 |
| playing            | string | 音频正在播放。 |
| paused             | string | 音频暂停播放。 |
| stopped            | string | 音频播放停止。 |
| error<sup>8+</sup> | string | 错误状态。     |

## MediaDescription<sup>8+</sup>

### [key : string] : any
Z
zengyawen 已提交
653

654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
通过key-value方式获取媒体信息

| 名称  | 类型   | 说明                                                         |
| ----- | ------ | ------------------------------------------------------------ |
| key   | string | 通过key值获取对应的value。key值具体可见[MediaDescriptionKey](#mediadescriptionkey8)。 |
| value | any    | 对应key值得value。其类型可为任意类型,具体key对应value的类型可参考[MediaDescriptionKey](#mediadescriptionkey8)的描述信息。 |

**示例:**

```js
function printfItemDescription(obj, key) {
    let property = obj[key];
    console.info('audio key is ' + key);
    console.info('audio value is ' + property);
}

audioPlayer.getTrackDescription((error, arrlist) => {
    if (typeof (arrlist) != 'undefined') {
        for (let i = 0; i < arrlist.length; i++) {
            printfItemDescription(arrlist[i], MD_KEY_TRACK_TYPE);  //打印出每条轨道MD_KEY_TRACK_TYPE的值
        }
    } else {
        console.log(`audio getTrackDescription fail, error:${error.message}`);
    }
});
```
Z
zengyawen 已提交
680 681 682

## AudioRecorder

683
音频录制管理类,用于录制音频媒体。在调用AudioRecorder的方法前,需要先通过[createAudioRecorder()](#media.createaudiorecorder)[createAudioRecorderAsync()](#media.createaudiorecorderasync8)构建一个[AudioRecorder](#audiorecorder)实例。
Z
zengyawen 已提交
684

685 686 687
音频录制demo可参考:[音频录制开发指导](../../media/audio-recorder.md)

### prepare<a name=audiorecorder_prepare></a>
Z
zengyawen 已提交
688 689 690 691 692 693 694 695 696

prepare(config: AudioRecorderConfig): void

录音准备。

**参数:**

| 参数名 | 类型                                        | 必填 | 说明                                                         |
| ------ | ------------------------------------------- | ---- | ------------------------------------------------------------ |
697
| config | [AudioRecorderConfig](#audiorecorderconfig) | 是   | 配置录音的相关参数,包括音频输出URI、[编码格式](#audioencoder)、采样率、声道数、[输出格式](#audiooutputformat)等。 |
Z
zengyawen 已提交
698 699 700

**示例:**

701
```js
Z
zengyawen 已提交
702
let audioRecorderConfig = {
703
    audioEncoder : media.AudioEncoder.AAC_LC,
Z
zengyawen 已提交
704 705 706
    audioEncodeBitRate : 22050,
    audioSampleRate : 22050,
    numberOfChannels : 2,
707 708 709
    format : media.AudioOutputFormat.AAC_ADTS,
    uri : 'file:///data/accounts/account_0/appdata/appdata/recorder/test.m4a',       // 文件需先由调用者创建,并给予适当的权限
    location : { latitude : 30, longitude : 130},
Z
zengyawen 已提交
710
}
711 712 713
audioRecorder.on('prepare', () => {    //设置'prepare'事件回调
    console.log('prepare success');
});
B
bird_j 已提交
714
audioRecorder.prepare(audioRecorderConfig);
Z
zengyawen 已提交
715 716 717
```


718
### start<a name=audiorecorder_start></a>
Z
zengyawen 已提交
719 720 721

start(): void

722
开始录制,需在[prepare](#on('prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset'))事件成功触发后,才能调用start方法。
Z
zengyawen 已提交
723 724 725

**示例:**

726 727 728 729 730
```js
audioRecorder.on('start', () => {    //设置'start'事件回调
    console.log('audio recorder start success');
});
audioRecorder.start();
Z
zengyawen 已提交
731
```
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760

### pause<a name=audiorecorder_pause></a>

pause():void

暂停录制,需要在[start](#on('prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset'))事件成功触发后,才能调用pause方法。

**示例:**

```js
audioRecorder.on('pause', () => {    //设置'pause'事件回调
    console.log('audio recorder pause success');
});
audioRecorder.pause();
```

### resume<a name=audiorecorder_resume></a>

resume():void

暂停录制,需要在[pause](#on('prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset'))事件成功触发后,才能调用resume方法。

**示例:**

```js
audioRecorder.on('resume', () => {    //设置'resume'事件回调
    console.log('audio recorder resume success');
});
audioRecorder.resume();
Z
zengyawen 已提交
761 762
```

763
### stop<a name=audiorecorder_stop></a>
Z
zengyawen 已提交
764 765 766 767 768 769 770

stop(): void

停止录音。

**示例:**

771 772 773 774 775
```js
audioRecorder.on('stop', () => {    //设置'stop'事件回调
    console.log('audio recorder stop success');
});
audioRecorder.stop();
Z
zengyawen 已提交
776 777
```

778
### release<a name=audiorecorder_release></a>
Z
zengyawen 已提交
779 780 781 782 783 784 785

release(): void

释放录音资源。

**示例:**

786
```js
B
bird_j 已提交
787 788 789
audioRecorder.on('release', () => {    //设置'release'事件回调
    console.log('audio recorder release success');
});
790 791
audioRecorder.release();
audioRecorder = undefined;
Z
zengyawen 已提交
792 793
```

794
### reset<a name=audiorecorder_reset></a>
Z
zengyawen 已提交
795 796 797 798 799

reset(): void

重置录音。

800
进行重置录音之前,需要先调用[stop()](#audiorecorder_stop)停止录音。重置录音之后,需要调用[prepare()](#audiorecorder_prepare)设置录音参数项,才能再次进行录音。
Z
zengyawen 已提交
801 802 803

**示例:**

B
bird_j 已提交
804 805 806 807 808
```js
audioRecorder.on('reset', () => {    //设置'reset'事件回调
    console.log('audio recorder reset success');
});
audioRecorder.reset();
Z
zengyawen 已提交
809 810
```

811
### on('prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset')
Z
zengyawen 已提交
812

813
on(type: 'prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset', callback: () => void): void
Z
zengyawen 已提交
814 815 816 817 818 819 820

开始订阅音频录制事件。

**参数:**

| 参数名   | 类型     | 必填 | 说明                                                         |
| -------- | -------- | ---- | ------------------------------------------------------------ |
821 822
| type     | string   | 是   | 录制事件回调类型,支持的事件包括:'prepare'&nbsp;\|&nbsp;'start'&nbsp;\|  'pause' \| ’resume‘ \|&nbsp;'stop'&nbsp;\|&nbsp;'release'&nbsp;\|&nbsp;'reset'。<br/>-&nbsp;'prepare'&nbsp;:完成[prepare](#audiorecorder_prepare)调用,音频录制参数设置完成,触发该事件。<br/>-&nbsp;'start'&nbsp;:完成[start](#audiorecorder_start)调用,音频录制开始,触发该事件。<br/>-&nbsp;'pause': 完成[pause](#audiorecorder_pause)调用,音频暂停录制,触发该事件。<br/>-&nbsp;'resume': 完成[resume](#audiorecorder_resume)调用,音频恢复录制,触发该事件。<br/>-&nbsp;'stop'&nbsp;:完成[stop](#audiorecorder_stop)调用,音频停止录制,触发该事件。<br/>-&nbsp;'release'&nbsp;:完成[release](#audiorecorder_release)调用,音频释放录制资源,触发该事件。<br/>-&nbsp;'reset':完成[reset](#audiorecorder_reset)调用,音频重置为初始状态,触发该事件。 |
| callback | ()=>void | 是   | 录制事件回调方法。                                           |
Z
zengyawen 已提交
823 824 825

**示例:**

826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
```js
let audiorecorder = media.createAudioRecorder();  								// 创建一个音频录制实例
let audioRecorderConfig = {
    audioEncoder : media.AudioEncoder.AAC_LC, ,
    audioEncodeBitRate : 22050,
    audioSampleRate : 22050,
    numberOfChannels : 2,
    format : media.AudioOutputFormat.AAC_ADTS,
    uri : 'file:///data/accounts/account_0/appdata/appdata/recorder/test.m4a',  // 文件需先由调用者创建,并给予适当的权限
    location : { latitude : 30, longitude : 130},
}
audioRecorder.on('error', (error) => {             								// 设置'error'事件回调
	console.info(`audio error called, errName is ${error.name}`);
    console.info(`audio error called, errCode is ${error.code}`);
    console.info(`audio error called, errMessage is ${error.message}`);
});
audioRecorder.on('prepare', () => {              								// 设置'prepare'事件回调
    console.log('prepare success');
    audioRecorder.start();                       								// 开始录制,并触发'start'事件回调
});
audioRecorder.on('start', () => {    		     								// 设置'start'事件回调
    console.log('audio recorder start success');
});
audioRecorder.on('pause', () => {    		     								// 设置'pause'事件回调
    console.log('audio recorder pause success');
});
audioRecorder.on('resume', () => {    		     								// 设置'resume'事件回调
    console.log('audio recorder resume success');
});
audioRecorder.on('stop', () => {    		     								// 设置'stop'事件回调
    console.log('audio recorder stop success');
});
audioRecorder.on('release', () => {    		     								// 设置'release'事件回调
    console.log('audio recorder release success');
});
audioRecorder.on('reset', () => {    		     								// 设置'reset'事件回调
    console.log('audio recorder reset success');
Z
zengyawen 已提交
863
});
B
bird_j 已提交
864
audioRecorder.prepare(audioRecorderConfig)       								// 设置录制参数 ,并触发'prepare'事件回调
Z
zengyawen 已提交
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
```

### on('error')

on(type: 'error', callback: ErrorCallback): void

开始订阅音频录制错误事件。

**参数:**

| 参数名   | 类型          | 必填 | 说明                                                         |
| -------- | ------------- | ---- | ------------------------------------------------------------ |
| type     | string        | 是   | 录制错误事件回调类型'error'。<br/>-&nbsp;'error':音频录制过程中发生错误,触发该事件。 |
| callback | ErrorCallback | 是   | 录制错误事件回调方法。                                       |

880 881 882 883 884 885 886 887 888 889
**示例:**

```js
audioRecorder.on('error', (error) => {      							// 设置'error'事件回调
	console.info(`audio error called, errName is ${error.name}`);       // 打印错误类型名称
    console.info(`audio error called, errCode is ${error.code}`);       // 打印错误码
    console.info(`audio error called, errMessage is ${error.message}`); // 打印错误类型详细描述
});
audioRecorder.prepare();  												// prepare不设置参数,触发'error'事件
```
Z
zengyawen 已提交
890 891 892 893 894

## AudioRecorderConfig

表示音频的录音配置。

895 896 897 898 899 900 901 902 903
| 名称                  | 参数类型                                | 必填 | 说明                                                         |
| --------------------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| audioEncoder          | [AudioEncoder](#audioencoder)           | 否   | 音频编码格式,默认设置为AAC_LC。                             |
| audioEncodeBitRate    | number                                  | 否   | 音频编码比特率,默认值为48000。                              |
| audioSampleRate       | number                                  | 否   | 音频采集采样率,默认值为48000。                              |
| numberOfChannels      | number                                  | 否   | 音频采集声道数,默认值为2。                                  |
| format                | [AudioOutputFormat](#audiooutputformat) | 否   | 音量输出封装格式,默认设置为MPEG_4。                         |
| location<sup>8+</sup> | [Location](#location8)                  | 否   | 音频采集的地理位置。                                         |
| uri                   | string                                  | 是   | 音频输出URI。支持:<br/>1.&nbsp;文件的绝对路径:file:///data/data/ohos.xxx.xxx/cache/test.mp4![zh-cn_image_0000001164217678](figures/zh-cn_image_0000001164217678.png)<br/>2.&nbsp;文件的fd路径:file://1&nbsp;(fd&nbsp;number)<br/> 文件需要由调用者创建,并赋予适当的权限。 |
Z
zengyawen 已提交
904 905 906 907 908 909 910 911 912 913 914 915 916 917


## AudioEncoder

表示音频编码格式的枚举。

| 名称   | 默认值 | 说明                                                         |
| ------ | ------ | ------------------------------------------------------------ |
| AAC_LC | 3      | AAC-LC(Advanced&nbsp;Audio&nbsp;Coding&nbsp;Low&nbsp;Complexity)编码格式。 |


## AudioOutputFormat

表示音频封装格式的枚举。
Z
zengyawen 已提交
918

Z
zengyawen 已提交
919 920 921
| 名称     | 默认值 | 说明                                                         |
| -------- | ------ | ------------------------------------------------------------ |
| MPEG_4   | 2      | 封装为MPEG-4格式。                                           |
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
| AAC_ADTS | 6      | 封装为ADTS(Audio&nbsp;Data&nbsp;Transport&nbsp;Stream)格式,是AAC音频的传输流格式。 |

## VideoRecorder<sup>8+</sup>

视频录制管理类,用于录制视频媒体。在调用VideoRecorder的方法前,需要先通过[createVideoRecorderAsync()](#media.createvideorecorderasync<sup>8+</sup>)构建一个[VideoRecorder](#videorecorder<sup>8+</sup>)实例。

视频录制demo可参考:[视频录制开发指导](../../media/video-recorder.md)

### 属性

| 名称  | 类型                                  | 可读 | 可写 | 说明             |
| ----- | ------------------------------------- | ---- | ---- | ---------------- |
| state | [VideoRecordState](#videorecordstate) | 是   | 否   | 视频录制的状态。 |

### prepare<a name=videorecorder_prepare1></a>

prepare(config: VideoRecorderConfig, callback: AsyncCallback\<void>): void;

异步方式进行视频录制的参数设置。通过注册回调函数获取返回值。

**参数:**

| 参数名   | 类型                                        | 必填 | 说明                                |
| -------- | ------------------------------------------- | ---- | ----------------------------------- |
| config   | [VideoRecorderConfig](#videorecorderconfig) | 是   | 配置视频录制的相关参数。            |
| callback | AsyncCallback\<void>                        | 是   | 异步视频录制prepare方法的回调方法。 |

**示例:**

```js
let videoProfile = {
    audioBitrate : 48000,
    audioChannels : 2,
    audioCodec : 'audio/mp4a-latm',
    audioSampleRate : 48000,
    fileFormat : 'mp4',
    videoBitrate : 48000,
    videoCodec : 'video/mp4v-es',
    videoFrameWidth : 640,
    videoFrameHeight : 480,
    videoFrameRate : 30
}

let videoConfig = {
    audioSourceType : 1,
    videoSourceType : 0,
    profile : videoProfile,
    url : 'file:///data/accounts/account_0/appdata/appdata/recorder/test.mp4',   // 文件需先由调用者创建,并给予适当的权限
    orientationHint : 0,
    location : { latitude : 30, longitude : 130 },
}

// asyncallback
let videoRecorder = null;
let events = require('events');
B
bird_j 已提交
977
let eventEmitter = new events.EventEmitter();                              
978 979 980 981

eventEmitter.on('prepare', () => {
    videoRecorder.prepare(videoConfig, (err) => {
        if (typeof (err) == 'undefined') {
B
bird_j 已提交
982
            console.info('prepare success');
983
        } else {
B
bird_j 已提交
984
            console.info('prepare failed and error is ' + err.message);
985 986 987 988 989 990
        }
    });
});

media.createVideoRecorder((err, recorder) => {
    if (typeof (err) == 'undefined' && typeof (recorder) != 'undefined') {
B
bird_j 已提交
991 992 993
        videoRecorder = recorder;
        console.info('createVideoRecorder success');
        eventEmitter.emit('prepare');                                        // prepare事件触发
994
    } else {
B
bird_j 已提交
995
        console.info('createVideoRecorder failed and error is ' + err.message);
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
    }
});
```

### prepare<a name=videorecorder_prepare2></a>

prepare(config: VideoRecorderConfig): Promise\<void>;

异步方式进行视频录制的参数设置。通过Promise获取返回值。

**参数:**

| 参数名 | 类型                                        | 必填 | 说明                     |
| ------ | ------------------------------------------- | ---- | ------------------------ |
| config | [VideoRecorderConfig](#videorecorderconfig) | 是   | 配置视频录制的相关参数。 |

**返回值:**

| 类型           | 说明                                     |
| -------------- | ---------------------------------------- |
| Promise\<void> | 异步视频录制prepare方法的Promise返回值。 |

**示例:**

```js
let videoProfile = {
    audioBitrate : 48000,
    audioChannels : 2,
    audioCodec : 'audio/mp4a-latm',
    audioSampleRate : 48000,
    fileFormat : 'mp4',
    videoBitrate : 48000,
    videoCodec : 'video/mp4v-es',
    videoFrameWidth : 640,
    videoFrameHeight : 480,
    videoFrameRate : 30
}

let videoConfig = {
    audioSourceType : 1,
    videoSourceType : 0,
    profile : videoProfile,
    url : 'file:///data/accounts/account_0/appdata/appdata/recorder/test.mp4',   // 文件需先由调用者创建,并给予适当的权限
    orientationHint : 0,
    location : { latitude : 30, longitude : 130 },
}

// promise
let videoRecorder = null;
await media.createVideoRecorder().then((recorder) => {
    if (typeof (recorder) != 'undefined') {
        videoRecorder = recorder;
        console.info('createVideoRecorder success');
    } else {
        console.info('createVideoRecorder failed');
    }
}, (err) => {
    console.info('error hanppend message is ' + err.message);
}).catch((err) => {
    console.info('catch err error message is ' + err.message);
});

await videoRecorder.prepare(videoConfig).then(() => {
    console.info('prepare success');
}, (err) => {
    console.info('prepare failed and error is ' + err.message);
}).catch((err) => {
    console.info('prepare failed and catch error is ' + err.message);
});
```

### getInputSurface

getInputSurface(callback: AsyncCallback\<string>): void;

异步方式获得录制需要的surface。此surface提供给调用者,调用者从此surface中获取surfaceBuffer,填入相应的数据。

应当注意,填入的视频数据需要携带时间戳(单位ns),buffersize。时间戳的起始时间请以系统启动时间为基准。

只能在[prepare()](#videorecorder_prepare1)接口调用后调用。

**参数:**

| 参数名   | 类型                   | 必填 | 说明                        |
| -------- | ---------------------- | ---- | --------------------------- |
| callback | AsyncCallback\<string> | 是   | 异步获得surface的回调方法。 |

**示例:**

```js
// asyncallback
B
bird_j 已提交
1087
let surfaceID = null;   											// 传递给外界的surfaceID
B
bird_j 已提交
1088 1089 1090
videoRecorder.getInputSurface((err, surfaceId) => {
    if (typeof (err) == 'undefined') {
        console.info('getInputSurface success');
B
bird_j 已提交
1091
        surfaceID = surfaceId;
B
bird_j 已提交
1092 1093 1094
    } else {
        console.info('getInputSurface failed and error is ' + err.message);
    }
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
});
```

### getInputSurface

getInputSurface(): Promise\<string>;

 异步方式获得录制需要的surface。此surface提供给调用者,调用者从此surface中获取surfaceBuffer,填入相应的数据。

应当注意,填入的视频数据需要携带时间戳(单位ns),buffersize。时间戳的起始时间请以系统启动时间为基准。

只能在[prepare()](#videorecorder_prepare1)接口调用后调用。

**返回值:**

| 类型             | 说明                             |
| ---------------- | -------------------------------- |
| Promise\<string> | 异步获得surface的Promise返回值。 |

**示例:**

```js
// promise
B
bird_j 已提交
1118 1119
let surfaceID = null;   											// 传递给外界的surfaceID
await videoRecorder.getInputSurface().then((surfaceId) => {
1120
    console.info('getInputSurface success');
B
bird_j 已提交
1121
    surfaceID = surfaceId;
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
}, (err) => {
    console.info('getInputSurface failed and error is ' + err.message);
}).catch((err) => {
    console.info('getInputSurface failed and catch error is ' + err.message);
});
```

### start<a name=videorecorder_start1></a>

start(callback: AsyncCallback\<void>): void;

异步方式开始视频录制。通过注册回调函数获取返回值。

[prepare()](#videorecorder_prepare1)[getInputSurface()](#getinputsurface)后调用,需要依赖数据源先给surface传递数据。

**参数:**

| 参数名   | 类型                 | 必填 | 说明                         |
| -------- | -------------------- | ---- | ---------------------------- |
| callback | AsyncCallback\<void> | 是   | 异步开始视频录制的回调方法。 |

**示例:**

```js
// asyncallback
B
bird_j 已提交
1147 1148 1149 1150 1151 1152
videoRecorder.start((err) => {
    if (typeof (err) == 'undefined') {
        console.info('start videorecorder success');
    } else {
        console.info('start videorecorder failed and error is ' + err.message);
    }
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
});
```

### start<a name=videorecorder_start2></a>

start(): Promise\<void>;

异步方式开始视频录制。通过Promise获取返回值。

[prepare()](#videorecorder_prepare1)[getInputSurface()](#getinputsurface)后调用,需要依赖数据源先给surface传递数据。

**返回值:**

| 类型           | 说明                                  |
| -------------- | ------------------------------------- |
| Promise\<void> | 异步开始视频录制方法的Promise返回值。 |

**示例:**

```js
// promise
await videoRecorder.start().then(() => {
    console.info('start videorecorder success');
}, (err) => {
    console.info('start videorecorder failed and error is ' + err.message);
}).catch((err) => {
    console.info('start videorecorder failed and catch error is ' + err.message);
});
```

### pause<a name=videorecorder_pause1></a>

pause(callback: AsyncCallback\<void>): void;

异步方式暂停视频录制。通过注册回调函数获取返回值。

[start()](#videorecorder_start1)后调用。可以通过调用[resume()](#videorecorder_resume1)接口来恢复录制。

**参数:**

| 参数名   | 类型                 | 必填 | 说明                         |
| -------- | -------------------- | ---- | ---------------------------- |
| callback | AsyncCallback\<void> | 是   | 异步暂停视频录制的回调方法。 |

**示例:**

```js
// asyncallback
B
bird_j 已提交
1201 1202 1203 1204 1205 1206
videoRecorder.pause((err) => {
    if (typeof (err) == 'undefined') {
        console.info('pause videorecorder success');
    } else {
        console.info('pause videorecorder failed and error is ' + err.message);
    }
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
});
```

### pause<a name=videorecorder_pause2></a>

pause(): Promise\<void>;

异步方式暂停视频录制。通过Promise获取返回值。

[start()](#videorecorder_start1)后调用。可以通过调用[resume()](#videorecorder_resume1)接口来恢复录制。

**返回值:**

| 类型           | 说明                                  |
| -------------- | ------------------------------------- |
| Promise\<void> | 异步暂停视频录制方法的Promise返回值。 |

**示例:**

```js
// promise
await videoRecorder.pause().then(() => {
    console.info('pause videorecorder success');
}, (err) => {
    console.info('pause videorecorder failed and error is ' + err.message);
}).catch((err) => {
    console.info('pause videorecorder failed and catch error is ' + err.message);
});
```

### resume<a name=videorecorder_resume1></a>

resume(callback: AsyncCallback\<void>): void;

异步方式恢复视频录制。通过注册回调函数获取返回值。

**参数:**

| 参数名   | 类型                 | 必填 | 说明                         |
| -------- | -------------------- | ---- | ---------------------------- |
| callback | AsyncCallback\<void> | 是   | 异步恢复视频录制的回调方法。 |

**示例:**

```js
// asyncallback
B
bird_j 已提交
1253 1254 1255 1256 1257 1258
videoRecorder.resume((err) => {
    if (typeof (err) == 'undefined') {
        console.info('resume videorecorder success');
    } else {
        console.info('resume videorecorder failed and error is ' + err.message);
    }
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
});
```

### resume<a name=videorecorder_resume2></a>

resume(): Promise\<void>;

异步方式恢复视频录制。通过Promise获取返回值。

**返回值:**

| 类型           | 说明                                  |
| -------------- | ------------------------------------- |
| Promise\<void> | 异步恢复视频录制方法的Promise返回值。 |

**示例:**

```js
// promise
await videoRecorder.resume().then(() => {
    console.info('resume videorecorder success');
}, (err) => {
    console.info('resume videorecorder failed and error is ' + err.message);
}).catch((err) => {
    console.info('resume videorecorder failed and catch error is ' + err.message);
});
```

### stop<a name=videorecorder_stop1></a>

stop(callback: AsyncCallback\<void>): void;

异步方式停止视频录制。通过注册回调函数获取返回值。

需要重新调用[prepare()](#videorecorder_prepare1)[getInputSurface()](#getinputsurface)接口才能重新录制。

**参数:**

| 参数名   | 类型                 | 必填 | 说明                         |
| -------- | -------------------- | ---- | ---------------------------- |
| callback | AsyncCallback\<void> | 是   | 异步停止视频录制的回调方法。 |

**示例:**

```js
// asyncallback
B
bird_j 已提交
1305 1306 1307 1308 1309 1310
videoRecorder.stop((err) => {
    if (typeof (err) == 'undefined') {
        console.info('stop videorecorder success');
    } else {
        console.info('stop videorecorder failed and error is ' + err.message);
    }
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
});
```

### stop<a name=videorecorder_stop2></a>

stop(): Promise\<void>;

异步方式停止视频录制。通过Promise获取返回值。

需要重新调用[prepare()](#videorecorder_prepare1)[getInputSurface()](#getinputsurface)接口才能重新录制。

**返回值:**

| 类型           | 说明                                  |
| -------------- | ------------------------------------- |
| Promise\<void> | 异步停止视频录制方法的Promise返回值。 |

**示例:**

```js
// promise
await videoRecorder.stop().then(() => {
    console.info('stop videorecorder success');
}, (err) => {
    console.info('stop videorecorder failed and error is ' + err.message);
}).catch((err) => {
    console.info('stop videorecorder failed and catch error is ' + err.message);
});
```

### release<a name=videorecorder_release1></a>

release(callback: AsyncCallback\<void>): void;

异步方式释放视频录制资源。通过注册回调函数获取返回值。

**参数:**

| 参数名   | 类型                 | 必填 | 说明                             |
| -------- | -------------------- | ---- | -------------------------------- |
| callback | AsyncCallback\<void> | 是   | 异步释放视频录制资源的回调方法。 |

**示例:**

```js
// asyncallback
B
bird_j 已提交
1357 1358 1359 1360 1361 1362
videoRecorder.release((err) => {
    if (typeof (err) == 'undefined') {
        console.info('release videorecorder success');
    } else {
        console.info('release videorecorder failed and error is ' + err.message);
    }
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408
});
```

### release<a name=videorecorder_release2></a>

release(): Promise\<void>;

异步方式释放视频录制资源。通过Promise获取返回值。

**返回值:**

| 类型           | 说明                                      |
| -------------- | ----------------------------------------- |
| Promise\<void> | 异步释放视频录制资源方法的Promise返回值。 |

**示例:**

```js
// promise
await videoRecorder.release().then(() => {
    console.info('release videorecorder success');
}, (err) => {
    console.info('release videorecorder failed and error is ' + err.message);
}).catch((err) => {
    console.info('release videorecorder failed and catch error is ' + err.message);
});
```

### reset<a name=videorecorder_reset1></a>

reset(callback: AsyncCallback\<void>): void;

异步方式重置视频录制。通过注册回调函数获取返回值。

需要重新调用[prepare()](#videorecorder_prepare1)[getInputSurface()](#getinputsurface)接口才能重新录制。

**参数:**

| 参数名   | 类型                 | 必填 | 说明                         |
| -------- | -------------------- | ---- | ---------------------------- |
| callback | AsyncCallback\<void> | 是   | 异步重置视频录制的回调方法。 |

**示例:**

```js
// asyncallback
B
bird_j 已提交
1409 1410 1411 1412 1413 1414
videoRecorder.reset((err) => {
    if (typeof (err) == 'undefined') {
        console.info('reset videorecorder success');
    } else {
        console.info('reset videorecorder failed and error is ' + err.message);
    }
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
});
```

### reset<a name=videorecorder_reset2></a>

reset(): Promise\<void>;

异步方式重置视频录制。通过Promise获取返回值。

需要重新调用[prepare()](#videorecorder_prepare1)[getInputSurface()](#getinputsurface)接口才能重新录制。

**返回值:**

| 类型           | 说明                                  |
| -------------- | ------------------------------------- |
| Promise\<void> | 异步重置视频录制方法的Promise返回值。 |

**示例:**

```js
// promise
await videoRecorder.reset().then(() => {
    console.info('reset videorecorder success');
}, (err) => {
    console.info('reset videorecorder failed and error is ' + err.message);
}).catch((err) => {
    console.info('reset videorecorder failed and catch error is ' + err.message);
});
```

### on('error')

on(type: 'error', callback: ErrorCallback): void

开始订阅视频录制错误事件。

**参数:**

| 参数名   | 类型          | 必填 | 说明                                                         |
| -------- | ------------- | ---- | ------------------------------------------------------------ |
| type     | string        | 是   | 录制错误事件回调类型'error'。<br/>-&nbsp;'error':音频录制过程中发生错误,触发该事件。 |
| callback | ErrorCallback | 是   | 录制错误事件回调方法。                                       |

**示例:**

```js
videoRecorder.on('error', (error) => {      							// 设置'error'事件回调
	console.info(`audio error called, errName is ${error.name}`);       // 打印错误类型名称
    console.info(`audio error called, errCode is ${error.code}`);       // 打印错误码
    console.info(`audio error called, errMessage is ${error.message}`); // 打印错误类型详细描述
});
// 当获取videoRecordState接口出错时通过此订阅事件上报
```

## VideoRecordState<sup>8+</sup>

视频录制的状态机。可通过state属性获取当前状态。

| 名称     | 类型   | 描述                   |
| -------- | ------ | ---------------------- |
| idle     | string | 视频录制空闲。         |
| prepared | string | 视频录制参数设置完成。 |
| playing  | string | 视频正在录制。         |
| paused   | string | 视频暂停录制。         |
| stopped  | string | 视频录制停止。         |
| error    | string | 错误状态。             |

## VideoRecorderConfig<sup>8+</sup>

表示视频录制的参数设置。

| 名称            | 参数类型                                                   | 必填 | 说明                                                         |
| --------------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ |
| audioSourceType | [AudioSourceType](#audiosourcetype<sup>8+</sup>)           | 是   | 视频录制的音频源类型。                                       |
| videoSourceType | [VideoSourceType](#videosourcetype<sup>8+</sup>)           | 是   | 视频录制的视频源类型。                                       |
| profile         | [VideoRecorderProfile](#videorecorderprofile<sup>8+</sup>) | 是   | 视频录制的profile。                                          |
| orientationHint | number                                                     | 否   | 录制视频的旋转角度。                                         |
| location        | [Location](#location8)                                     | 否   | 录制视频的地理位置。                                         |
| uri             | string                                                     | 是   | 视频输出URI。支持:<br/>1.&nbsp;文件的绝对路径:file:///data/data/ohos.xxx.xxx/cache/test.mp4![zh-cn_image_0000001164217678](figures/zh-cn_image_0000001164217678.png)<br/>2.&nbsp;文件的fd路径:file://1&nbsp;(fd&nbsp;number)<br/> 文件需要由调用者创建,并赋予适当的权限。 |

## AudioSourceType<sup>8+</sup>

表示视频录制中音频源类型的枚举。

| 名称                       | 值   | 说明                   |
| -------------------------- | ---- | ---------------------- |
| AUDIO_SOURCE_TYPE_DEFAULT0 | 0    | 默认的音频输入源类型。 |
| AUDIO_SOURCE_TYPE_MIC      | 1    | 表示MIC的音频输入源。  |

## VideoSourceType<sup>8+</sup>

表示视频录制中视频源类型的枚举。

| 名称                          | 值   | 说明                            |
| ----------------------------- | ---- | ------------------------------- |
| VIDEO_SOURCE_TYPE_SURFACE_YUV | 0    | 输入surface中携带的是raw data。 |
| VIDEO_SOURCE_TYPE_SURFACE_ES  | 1    | 输入surface中携带的是ES data。  |

## VideoRecorderProfile<sup>8+</sup>

视频录制的配置文件。

| 名称             | 参数类型                                     | 必填 | 说明             |
| ---------------- | -------------------------------------------- | ---- | ---------------- |
| audioBitrate     | number                                       | 是   | 音频编码比特率。 |
| audioChannels    | number                                       | 是   | 音频采集声道数。 |
| audioCodec       | [CodecMimeType](#CodecMimeType8)             | 是   | 音频编码格式。   |
| audioSampleRate  | number                                       | 是   | 音频采样率。     |
| fileFormat       | [ContainerFormatType](#containerformattype8) | 是   | 文件的容器格式。 |
| videoCodec       | [CodecMimeType](#CodecMimeType8)             | 是   | 视频编码格式。   |
| videoFrameWidth  | number                                       | 是   | 录制视频帧的宽。 |
| videoFrameHeight | number                                       | 是   | 录制视频帧的高。 |

## ContainerFormatType<sup>8+</sup>

表示容器格式类型的枚举,缩写为CFT。

| 名称        | 值    | 说明                  |
| ----------- | ----- | --------------------- |
| CFT_MPEG_4  | "mp4" | 视频的容器格式,MP4。 |
| CFT_MPEG_4A | "m4a" | 音频的容器格式,M4A。 |

## Location<sup>8+</sup>

视频录制的地理位置。

| 名称      | 参数类型 | 必填 | 说明             |
| --------- | -------- | ---- | ---------------- |
| latitude  | number   | 是   | 地理位置的纬度。 |
| longitude | number   | 是   | 地理位置的经度。 |