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

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

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

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

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

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

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

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

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

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

26 27


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

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

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

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

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

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

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

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

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

**示例:**

54 55 56 57 58 59 60 61 62
```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 已提交
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 94

## 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 已提交
95
```
96

97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 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
## media.createVideoPlayer<sup>8+</sup>

createVideoPlayer(callback: AsyncCallback\<[VideoPlayer](#videoplayer8)>): void

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

**参数:**

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

**示例:**

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

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

createVideoPlayer: Promise<[VideoPlayer](#videoplayer8)>

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

**返回值:**

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

**示例:**

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

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

Z
zengyawen 已提交
154
## media.createAudioRecorder
155

Z
zengyawen 已提交
156
createAudioRecorder(): AudioRecorder
Z
zengyawen 已提交
157

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

Z
zengyawen 已提交
160
**返回值:**
Z
zengyawen 已提交
161

Z
zengyawen 已提交
162 163 164
| 类型                            | 说明                                      |
| ------------------------------- | ----------------------------------------- |
| [AudioRecorder](#audiorecorder) | 返回AudioRecorder类实例,失败时返回null。 |
Z
zengyawen 已提交
165

Z
zengyawen 已提交
166
**示例:**
167

168
```js
B
bird_j 已提交
169
let audiorecorder = media.createAudioRecorder(); 
Z
zengyawen 已提交
170
```
Z
zengyawen 已提交
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 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 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
## 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);
```



288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
## 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类型枚举

| 名称         | 值                | 说明                     |
| ------------ | ----------------- | ------------------------ |
321
| VIDEO_MPEG4  | ”video/mp4v-es“   | 表示视频/mpeg4类型。     |
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
| 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 已提交
355
## AudioPlayer
Z
zengyawen 已提交
356

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

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

361
### 属性<a name=audioplayer_属性></a>
Z
zengyawen 已提交
362

363 364 365 366 367 368 369
| 名称        | 类型                      | 可读 | 可写 | 说明                                                         |
| ----------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ |
| 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 已提交
370

371
### play<a name=audioplayer_play></a>
Z
zengyawen 已提交
372

Z
zengyawen 已提交
373
play(): void
Z
zengyawen 已提交
374

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

Z
zengyawen 已提交
377
**示例:**
Z
zengyawen 已提交
378

379 380 381
```js
audioPlayer.on('play', () => {    //设置'play'事件回调
    console.log('audio play success');
Z
zengyawen 已提交
382
});
383
audioPlayer.play();
Z
zengyawen 已提交
384
```
Z
zengyawen 已提交
385

386
### pause<a name=audioplayer_pause></a>
Z
zengyawen 已提交
387

Z
zengyawen 已提交
388
pause(): void
Z
zengyawen 已提交
389

Z
zengyawen 已提交
390
暂停播放音频资源。
Z
zengyawen 已提交
391

Z
zengyawen 已提交
392
**示例:**
Z
zengyawen 已提交
393

394 395 396
```js
audioPlayer.on('pause', () => {    //设置'pause'事件回调
    console.log('audio pause success');
Z
zengyawen 已提交
397
});
398
audioPlayer.pause();
Z
zengyawen 已提交
399
```
Z
zengyawen 已提交
400

401
### stop<a name=audioplayer_stop></a>
Z
zengyawen 已提交
402

Z
zengyawen 已提交
403
stop(): void
Z
zengyawen 已提交
404

Z
zengyawen 已提交
405
停止播放音频资源。
Z
zengyawen 已提交
406

Z
zengyawen 已提交
407
**示例:**
Z
zengyawen 已提交
408

409 410 411 412 413
```js
audioPlayer.on('stop', () => {    //设置'stop'事件回调
    console.log('audio stop success');
});
audioPlayer.stop();
Z
zengyawen 已提交
414
```
415 416 417 418 419 420 421 422 423 424 425 426

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

reset(): void

切换播放音频资源。

**示例:**

```js
audioPlayer.on('reset', () => {    //设置'reset'事件回调
    console.log('audio reset success');
Z
zengyawen 已提交
427
});
428
audioPlayer.reset();
Z
zengyawen 已提交
429
```
Z
zengyawen 已提交
430

431
### seek<a name=audioplayer_seek></a>
Z
zengyawen 已提交
432

Z
zengyawen 已提交
433
seek(timeMs: number): void
Z
zengyawen 已提交
434

Z
zengyawen 已提交
435
跳转到指定播放位置。
Z
zengyawen 已提交
436

Z
zengyawen 已提交
437
**参数:**
Z
zengyawen 已提交
438

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

Z
zengyawen 已提交
443
**示例:**
Z
zengyawen 已提交
444

445 446 447 448 449 450 451
```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 已提交
452
});
453
audioPlayer.seek(30000);    //seek到30000ms的位置
Z
zengyawen 已提交
454
```
Z
zengyawen 已提交
455

456
### setVolume<a name=audioplayer_setvolume></a>
Z
zengyawen 已提交
457

Z
zengyawen 已提交
458
setVolume(vol: number): void
Z
zengyawen 已提交
459

Z
zengyawen 已提交
460
设置音量。
Z
zengyawen 已提交
461

Z
zengyawen 已提交
462
**参数:**
Z
zengyawen 已提交
463

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

Z
zengyawen 已提交
468
**示例:**
Z
zengyawen 已提交
469

470 471 472
```js
audioPlayer.on('volumeChange', () => {    //设置'volumeChange'事件回调
    console.log('audio volumeChange success');
Z
zengyawen 已提交
473
});
474
audioPlayer.setVolume(1);    //设置音量到100%
Z
zengyawen 已提交
475
```
Z
zengyawen 已提交
476

477
### release<a name=audioplayer_release></a>
Z
zengyawen 已提交
478

479
release(): void
Z
zengyawen 已提交
480

481
释放音频资源。
Z
zengyawen 已提交
482

Z
zengyawen 已提交
483
**示例:**
Z
zengyawen 已提交
484

485 486 487
```js
audioPlayer.release();
audioPlayer = undefined;
Z
zengyawen 已提交
488
```
Z
zengyawen 已提交
489

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

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

494 495 496 497 498 499 500
通过回调方式获取音频轨道信息。

**参数:**

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

Z
zengyawen 已提交
502
**示例:**
Z
zengyawen 已提交
503

504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
```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 已提交
522
```
523 524 525 526 527 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

### 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 已提交
563 564
```

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

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

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

Z
zengyawen 已提交
571 572
**参数:**

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

**示例:**

580 581 582 583 584
```js
audioPlayer.on('bufferingUpdate', (infoType, value) => {
    console.log('audio bufferingInfo type: ' + infoType);
    console.log('audio bufferingInfo value: ' + value);
});
Z
zengyawen 已提交
585
```
586 587 588 589 590 591 592 593 594 595 596

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

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

开始订阅音频播放事件。

**参数:**

| 参数名   | 类型       | 必填 | 说明                                                         |
| -------- | ---------- | ---- | ------------------------------------------------------------ |
597
| type     | string     | 是   | 播放事件回调类型,支持的事件包括:'play' \| 'pause' \| 'stop' \| 'reset' \| 'dataLoad' \| 'finish' \| 'volumeChange'。<br>- 'play':完成[play()](#play)调用,音频开始播放,触发该事件。<br>- 'pause':完成[pause()](#pause)调用,音频暂停播放,触发该事件。<br>- 'stop':完成[stop()](#stop)调用,音频停止播放,触发该事件。<br>- 'reset':完成[reset()](#reset7)调用,播放器重置,触发该事件。<br>- 'dataLoad':完成音频数据加载后触发该事件,即src属性设置完成后触发该事件。<br>- 'finish':完成音频播放后触发该事件。<br>- 'volumeChange':完成[setVolume()](#setvolume)调用,播放音量改变后触发该事件。 |
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
| 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 已提交
641
});
642
audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp4';  //设置src属性,并触发'dataLoad'事件回调
Z
zengyawen 已提交
643 644 645 646 647
```

### on('timeUpdate')

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

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

Z
zengyawen 已提交
651 652
**参数:**

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

**示例:**

660 661 662 663 664 665 666
```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 已提交
667
});
668
audioPlayer.seek(30000);    //seek到30000ms的位置
Z
zengyawen 已提交
669 670 671 672 673
```

### on('error')

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

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

Z
zengyawen 已提交
677 678
**参数:**

679 680 681 682
| 参数名   | 类型          | 必填 | 说明                                                         |
| -------- | ------------- | ---- | ------------------------------------------------------------ |
| type     | string        | 是   | 播放错误事件回调类型,支持的事件包括:'error'。<br>- 'error':音频播放中发生错误,触发该事件。 |
| callback | ErrorCallback | 是   | 播放错误事件回调方法。                                       |
Z
zengyawen 已提交
683 684 685

**示例:**

686 687 688 689 690
```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 已提交
691
});
692
audioPlayer.setVolume(3);  //设置volume为无效值,触发'error'事件
Z
zengyawen 已提交
693 694 695
```

## AudioState
Z
zengyawen 已提交
696

697 698 699 700 701 702 703 704 705 706
音频播放的状态机。可通过state属性获取当前状态。

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

707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 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 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 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 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 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 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 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 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 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 1147 1148 1149 1150 1151 1152 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 1201 1202 1203 1204 1205 1206 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 1253 1254 1255 1256 1257 1258 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 1305 1306 1307 1308 1309 1310 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 1357 1358 1359 1360 1361 1362 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 1409 1410 1411 1412 1413 1414 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
## VideoPlayer<sup>8+</sup>

视频播放管理类,用于管理和播放视频媒体。在调用VideoPlayer的方法前,需要先通过[createVideoPlayer()](#media.createvideoplayer8)构建一个[VideoPlayer](#videoplayer8)实例。

视频播放demo可参考:[视频播放开发指导](../../media/video-playback.md)

### 属性<a name=videoplayer_属性></a><sup>8+</sup>

| 名称        | 类型                               | 可读 | 可写 | 说明                                                         |
| ----------- | ---------------------------------- | ---- | ---- | ------------------------------------------------------------ |
| url         | string                             | 是   | 是   | 视频媒体URL,支持当前主流的视频格式(mp4、mpeg-ts、webm、mkv)。<br>**支持路径示例**<br>1. 本地绝对路径:file:///data/data/ohos.xxx.xxx/files/test.mp4<br>![zh-cn_image_0000001164217678](figures/zh-cn_image_0000001164217678.png)<br>**注意事项**<br>媒体素材需至少赋予读权限后,才可正常播放 |
| loop        | boolean                            | 是   | 是   | 视频循环播放属性,设置为'true'表示循环播放。                 |
| currentTime | number                             | 是   | 否   | 视频的当前播放位置。                                         |
| duration    | number                             | 是   | 否   | 视频时长,返回-1表示直播模式                                 |
| state       | [VideoPlayState](#videoplaystate8) | 是   | 否   | 视频播放的状态。                                             |
| width       | number                             | 是   | 否   | 视频宽。                                                     |
| height      | number                             | 是   | 否   | 视频高。                                                     |

### setDisplaySurface<sup>8+</sup>

setDisplaySurface(surfaceId: string, callback: AsyncCallback\<void>): void

通过回调方式设置SurfaceId。

**参数:**

| 参数名    | 类型     | 必填 | 说明                      |
| --------- | -------- | ---- | ------------------------- |
| surfaceId | string   | 是   | SurfaceId                 |
| callback  | function | 是   | 设置SurfaceId的回调方法。 |

**示例:**

```js
videoPlayer.setDisplaySurface(surfaceId, (err) => {
	if (typeof (err) == 'undefined') {
		console.info('setDisplaySurface success!');
	} else {
        console.info('setDisplaySurface fail!');
    }
});
```

### setDisplaySurface<sup>8+</sup>

setDisplaySurface(surfaceId: string): Promise\<void>

通过Promise方式设置SurfaceId。

**参数:**

| 参数名    | 类型   | 必填 | 说明      |
| --------- | ------ | ---- | --------- |
| surfaceId | string | 是   | SurfaceId |

**返回值:**

| 类型          | 说明                           |
| ------------- | ------------------------------ |
| Promise<void> | 设置SurfaceId的Promise返回值。 |

**示例:**

```js
function failureCallback(error) {
    console.info(`video failureCallback, error:${error.message}`);
}
function catchCallback(error) {
    console.info(`video catchCallback, error:${error.message}`);
}
await videoPlayer.setDisplaySurface(surfaceId).then(() => {
    console.info('setDisplaySurface success');
}, failureCallback).catch(catchCallback);
```

### prepare<sup>8+</sup>

prepare(callback: AsyncCallback\<void>): void

通过回调方式准备播放视频。

**参数:**

| 参数名   | 类型     | 必填 | 说明                     |
| -------- | -------- | ---- | ------------------------ |
| callback | function | 是   | 准备播放视频的回调方法。 |

**示例:**

```js
videoPlayer.prepare((err) => {
	if (typeof (err) == 'undefined') {
		console.info('prepare success!');
	} else {
        console.info('prepare fail!');
    }
});
```

### prepare<sup>8+</sup>

prepare(): Promise\<void>

通过Promise方式准备播放视频。

**返回值:**

| 类型           | 说明                          |
| -------------- | ----------------------------- |
| Promise\<void> | 准备播放视频的Promise返回值。 |

**示例:**

```js
function failureCallback(error) {
    console.info(`video failureCallback, error:${error.message}`);
}
function catchCallback(error) {
    console.info(`video catchCallback, error:${error.message}`);
}
await videoPlayer.prepare().then(() => {
    console.info('prepare success');
}, failureCallback).catch(catchCallback);
```

### play<sup>8+</sup>

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

通过回调方式开始播放视频。

**参数:**

| 参数名   | 类型     | 必填 | 说明                     |
| -------- | -------- | ---- | ------------------------ |
| callback | function | 是   | 开始播放视频的回调方法。 |

**示例:**

```js
videoPlayer.play((err) => {
	if (typeof (err) == 'undefined') {
		console.info('play success!');
	} else {
        console.info('play fail!');
    }
});
```

### play<sup>8+</sup>

play(): Promise\<void>;

通过Promise方式开始播放视频。

**返回值:**

| 类型           | 说明                          |
| -------------- | ----------------------------- |
| Promise\<void> | 开始播放视频的Promise返回值。 |

**示例:**

```js
function failureCallback(error) {
    console.info(`video failureCallback, error:${error.message}`);
}
function catchCallback(error) {
    console.info(`video catchCallback, error:${error.message}`);
}
await videoPlayer.play().then(() => {
    console.info('play success');
}, failureCallback).catch(catchCallback);
```

### pause<sup>8+</sup>

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

通过回调方式暂停播放视频。

**参数:**

| 参数名   | 类型     | 必填 | 说明                     |
| -------- | -------- | ---- | ------------------------ |
| callback | function | 是   | 暂停播放视频的回调方法。 |

**示例:**

```js
videoPlayer.pause((err) => {
	if (typeof (err) == 'undefined') {
		console.info('pause success!');
	} else {
        console.info('pause fail!');
    }
});
```

### pause<sup>8+</sup>

pause(): Promise\<void>

通过Promise方式暂停播放视频。

**返回值:**

| 类型           | 说明                          |
| -------------- | ----------------------------- |
| Promise\<void> | 暂停播放视频的Promise返回值。 |

**示例:**

```js
function failureCallback(error) {
    console.info(`video failureCallback, error:${error.message}`);
}
function catchCallback(error) {
    console.info(`video catchCallback, error:${error.message}`);
}
await videoPlayer.pause().then(() => {
    console.info('pause success');
}, failureCallback).catch(catchCallback);
```

### stop<sup>8+</sup>

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

通过回调方式停止播放视频。

**参数:**

| 参数名   | 类型     | 必填 | 说明                     |
| -------- | -------- | ---- | ------------------------ |
| callback | function | 是   | 停止播放视频的回调方法。 |

**示例:**

```js
videoPlayer.stop((err) => {
	if (typeof (err) == 'undefined') {
		console.info('stop success!');
	} else {
        console.info('stop fail!');
    }
});
```

### stop<sup>8+</sup>

stop(): Promise\<void>

通过Promise方式停止播放视频。

**返回值:**

| 类型           | 说明                          |
| -------------- | ----------------------------- |
| Promise\<void> | 停止播放视频的Promise返回值。 |

**示例:**

```js
function failureCallback(error) {
    console.info(`video failureCallback, error:${error.message}`);
}
function catchCallback(error) {
    console.info(`video catchCallback, error:${error.message}`);
}
await videoPlayer.stop().then(() => {
    console.info('stop success');
}, failureCallback).catch(catchCallback);
```

### reset<sup>8+</sup>

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

通过回调方式切换播放视频。

**参数:**

| 参数名   | 类型     | 必填 | 说明                     |
| -------- | -------- | ---- | ------------------------ |
| callback | function | 是   | 切换播放视频的回调方法。 |

**示例:**

```js
videoPlayer.reset((err) => {
	if (typeof (err) == 'undefined') {
		console.info('reset success!');
	} else {
        console.info('reset fail!');
    }
});
```

### reset<sup>8+</sup>

reset(): Promise\<void>

通过Promise方式切换播放视频。

**返回值:**

| 类型           | 说明                          |
| -------------- | ----------------------------- |
| Promise\<void> | 切换播放视频的Promise返回值。 |

**示例:**

```js
function failureCallback(error) {
    console.info(`video failureCallback, error:${error.message}`);
}
function catchCallback(error) {
    console.info(`video catchCallback, error:${error.message}`);
}
await videoPlayer.reset().then(() => {
    console.info('reset success');
}, failureCallback).catch(catchCallback);
```

### seek<sup>8+</sup>

seek(timeMs: number, callback: AsyncCallback\<number>): void

通过回调方式跳转到指定播放位置,默认跳转到指定时间点的下一个关键帧。

**参数:**

| 参数名   | 类型     | 必填 | 说明                           |
| -------- | -------- | ---- | ------------------------------ |
| timeMs   | number   | 是   | 指定的跳转时间节点,单位毫秒。 |
| callback | function | 是   | 跳转到指定播放位置的回调方法。 |

**示例:**

```js
videoPlayer.seek((seekTime, err) => {
	if (typeof (err) == 'undefined') {
		console.info('seek success!');
	} else {
        console.info('seek fail!');
    }
});
```

### seek<sup>8+</sup>

seek(timeMs: number, mode:SeekMode, callback: AsyncCallback\<number>): void

通过回调方式跳转到指定播放位置。

**参数:**

| 参数名   | 类型     | 必填 | 说明                                     |
| -------- | -------- | ---- | ---------------------------------------- |
| timeMs   | number   | 是   | 指定的跳转时间节点,单位毫秒。           |
| mode     | SeekMode | 是   | 跳转模式,具体见[SeekMode](#seekmode8)。 |
| callback | function | 是   | 跳转到指定播放位置的回调方法。           |

**示例:**

```js
videoPlayer.seek((seekTime, seekMode, err) => {
	if (typeof (err) == 'undefined') {
		console.info('seek success!');
	} else {
        console.info('seek fail!');
    }
});
```

### seek<sup>8+</sup>

seek(timeMs: number, mode?:SeekMode): Promise\<number>

通过Promise方式跳转到指定播放位置,如果没有设置mode则跳转到指定时间点的下一个关键帧。

**参数:**

| 参数名 | 类型     | 必填 | 说明                                   |
| ------ | -------- | ---- | -------------------------------------- |
| timeMs | number   | 是   | 指定的跳转时间节点,单位毫秒。         |
| mode   | SeekMode | 否   | 跳转模式,具体见[SeekMode](#seekmode8) |

**返回值:**

| 类型           | 说明                                |
| -------------- | ----------------------------------- |
| Promise\<void> | 跳转到指定播放位置的Promise返回值。 |

**示例:**

```js
function failureCallback(error) {
    console.info(`video failureCallback, error:${error.message}`);
}
function catchCallback(error) {
    console.info(`video catchCallback, error:${error.message}`);
}
await videoPlayer.seek(seekTime).then((seekDoneTime) => { // seekDoneTime表示seek完成后的时间点
    console.info('seek success');
}, failureCallback).catch(catchCallback);

await videoPlayer.seek(seekTime, seekMode).then((seekDoneTime) => {
    console.info('seek success');
}, failureCallback).catch(catchCallback);
```

### setVolume<sup>8+</sup>

setVolume(vol: number, callback: AsyncCallback\<void>): void

通过回调方式设置音量。

**参数:**

| 参数名   | 类型     | 必填 | 说明                                                         |
| -------- | -------- | ---- | ------------------------------------------------------------ |
| vol      | number   | 是   | 指定的相对音量大小,取值范围为[0.00-1.00],1表示最大音量,即100%。 |
| callback | function | 是   | 设置音量的回调方法。                                         |

**示例:**

```js
videoPlayer.setVolume((vol, err) => {
	if (typeof (err) == 'undefined') {
		console.info('setVolume success!');
	} else {
        console.info('setVolume fail!');
    }
});
```

### setVolume<sup>8+</sup>

setVolume(vol: number): Promise\<void>

通过Promise方式设置音量。

**参数:**

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

**返回值:**

| 类型           | 说明                      |
| -------------- | ------------------------- |
| Promise\<void> | 设置音量的Promise返回值。 |

**示例:**

```js
function failureCallback(error) {
    console.info(`video failureCallback, error:${error.message}`);
}
function catchCallback(error) {
    console.info(`video catchCallback, error:${error.message}`);
}
await videoPlayer.setVolume(vol).then() => {
    console.info('setVolume success');
}, failureCallback).catch(catchCallback);
```

### release<sup>8+</sup>

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

通过回调方式释放视频资源。

**参数:**

| 参数名   | 类型     | 必填 | 说明                     |
| -------- | -------- | ---- | ------------------------ |
| callback | function | 是   | 释放视频资源的回调方法。 |

**示例:**

```js
videoPlayer.release((err) => {
	if (typeof (err) == 'undefined') {
		console.info('release success!');
	} else {
        console.info('release fail!');
    }
});
```

### release<sup>8+</sup>

release(): Promise\<void>

通过Promise方式释放视频资源。

**返回值:**

| 类型           | 说明                          |
| -------------- | ----------------------------- |
| Promise\<void> | 释放视频资源的Promise返回值。 |

**示例:**

```js
function failureCallback(error) {
    console.info(`video failureCallback, error:${error.message}`);
}
function catchCallback(error) {
    console.info(`video catchCallback, error:${error.message}`);
}
await videoPlayer.release().then() => {
    console.info('release success');
}, failureCallback).catch(catchCallback);
```

### getTrackDescription<sup>8+</sup>

getTrackDescription(callback: AsyncCallback<Array<[MediaDescription](#mediadescription8>>)>>): void

通过回调方式获取视频轨道信息。

**参数:**

| 参数名   | 类型     | 必填 | 说明                       |
| -------- | -------- | ---- | -------------------------- |
| callback | function | 是   | 获取视频轨道信息回调方法。 |

**示例:**

```js
function printfDescription(obj) {
    for (let item in obj) {
        let property = obj[item];
        console.info('video key is ' + item);
        console.info('video value is ' + property);
    }
}

videoPlayer.getTrackDescription((error, arrlist) => {
    if (typeof (arrlist) != 'undefined') {
        for (let i = 0; i < arrlist.length; i++) {
            printfDescription(arrlist[i]);
        }
    } else {
        console.log(`video getTrackDescription fail, error:${error.message}`);
    }
});
```

### getTrackDescription<sup>8+</sup>

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('video key is ' + item);
        console.info('video value is ' + property);
    }
}
function failureCallback(error) {
    console.info(`video failureCallback, error:${error.message}`);
}
function catchCallback(error) {
    console.info(`video catchCallback, error:${error.message}`);
}

let arrayDescription;
await videoPlayer.getTrackDescription().then((arrlist) => {
    if (typeof (arrlist) != 'undefined') {
        arrayDescription = arrlist;
    } else {
        console.log('video getTrackDescription fail');
    }
}, failureCallback).catch(catchCallback);
for (let i = 0; i < arrayDescription.length; i++) {
    printfDescription(arrayDescription[i]);
}
```

### setSpeed<sup>8+</sup>

setSpeed(speed:number, callback: AsyncCallback\<number>): void

通过回调方式设置播放速度。

**参数:**

| 参数名   | 类型     | 必填 | 说明                                                       |
| -------- | -------- | ---- | ---------------------------------------------------------- |
| speed    | number   | 是   | 指定播放视频速度,具体见[PlaybackSpeed](#playbackspeed8)。 |
| callback | function | 是   | 设置播放速度的回调方法。                                   |

**示例:**

```js
videoPlayer.setSpeed((speed:number, err) => {
	if (typeof (err) == 'undefined') {
		console.info('setSpeed success!');
	} else {
        console.info('setSpeed fail!');
    }
});
```

### setSpeed<sup>8+</sup>

setSpeed(speed:number): Promise\<number>

通过Promise方式设置播放速度。

**参数:**

| 参数名 | 类型   | 必填 | 说明                                                       |
| ------ | ------ | ---- | ---------------------------------------------------------- |
| speed  | number | 是   | 指定播放视频速度,具体见[PlaybackSpeed](#playbackspeed8)。 |

**示例:**

```js
function failureCallback(error) {
    console.info(`video failureCallback, error:${error.message}`);
}
function catchCallback(error) {
    console.info(`video catchCallback, error:${error.message}`);
}
await videoPlayer.setSpeed(speed).then() => {
    console.info('setSpeed success');
}, failureCallback).catch(catchCallback);
```

### on('playbackCompleted')<sup>8+</sup>

on(type: 'playbackCompleted', callback: Callback\<void>): void

开始监听视频播放完成事件。

**参数:**

| 参数名   | 类型     | 必填 | 说明                                                        |
| -------- | -------- | ---- | ----------------------------------------------------------- |
| type     | string   | 是   | 视频播放完成事件回调类型,支持的事件:'playbackCompleted'。 |
| callback | function | 是   | 视频播放完成事件回调方法。                                  |

**示例:**

```js
videoPlayer.on('playbackCompleted', () => {
	console.info('playbackCompleted success!');
});
```

### on('bufferingUpdate')<sup>8+</sup>

on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void

开始监听视频缓存更新事件。

**参数:**

| 参数名   | 类型     | 必填 | 说明                                                         |
| -------- | -------- | ---- | ------------------------------------------------------------ |
| type     | string   | 是   | 视频缓存事件回调类型,支持的事件:'bufferingUpdate'。        |
| callback | function | 是   | 视频缓存事件回调方法。<br>[BufferingInfoType](#bufferinginfotype8)为BUFFERING_PERCENT或CACHED_DURATION时,value值有效,否则固定为0。 |

**示例:**

```js
videoPlayer.on('bufferingUpdate', (infoType, value) => {
    console.log('video bufferingInfo type: ' + infoType);
    console.log('video bufferingInfo value: ' + value);
});
```

### on('startRenderFrame')<sup>8+</sup>

on(type: 'startRenderFrame', callback: Callback\<void>): void

开始监听视频播放首帧送显上报事件。

**参数:**

| 参数名   | 类型     | 必填 | 说明                                                         |
| -------- | -------- | ---- | ------------------------------------------------------------ |
| type     | string   | 是   | 视频播放首帧送显上报事件回调类型,支持的事件:'startRenderFrame'。 |
| callback | function | 是   | 视频播放首帧送显上报事件回调方法。                           |

**示例:**

```js
videoPlayer.on('startRenderFrame', () => {
	console.info('startRenderFrame success!');
});
```

### on('videoSizeChanged')<sup>8+</sup>

on(type: 'videoSizeChanged', callback: (width: number, height: number) => void): void

开始监听视频播放宽高变化事件。

**参数:**

| 参数名   | 类型     | 必填 | 说明                                                         |
| -------- | -------- | ---- | ------------------------------------------------------------ |
| type     | string   | 是   | 视频播放宽高变化事件回调类型,支持的事件:'videoSizeChanged'。 |
| callback | function | 是   | 视频播放宽高变化事件回调方法,width表示宽,height表示高。    |

**示例:**

```js
videoPlayer.on('videoSizeChanged', (width, height) => {
    console.log('video width is: ' + width);
    console.log('video height is: ' + height);
});
```

### on('error')<sup>8+</sup>

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

开始监听视频播放错误事件。

**参数:**

| 参数名   | 类型     | 必填 | 说明                                                         |
| -------- | -------- | ---- | ------------------------------------------------------------ |
| type     | string   | 是   | 播放错误事件回调类型,支持的事件包括:'error'。<br>- 'error':视频播放中发生错误,触发该事件。 |
| callback | function | 是   | 播放错误事件回调方法。                                       |

**示例:**

```js
videoPlayer.on('error', (error) => {      // 设置'error'事件回调
	console.info(`video error called, errName is ${error.name}`);      // 打印错误类型名称
    console.info(`video error called, errCode is ${error.code}`);      // 打印错误码
    console.info(`video error called, errMessage is ${error.message}`);// 打印错误类型详细描述
});
videoPlayer.setVolume(3);  //设置volume为无效值,触发'error'事件
```

## VideoPlayState<sup>8+</sup>

视频播放的状态机,可通过state属性获取当前状态。

| 名称     | 类型   | 描述           |
| -------- | ------ | -------------- |
| idle     | string | 视频播放空闲。 |
| prepared | string | 视频播放准备。 |
| playing  | string | 视频正在播放。 |
| paused   | string | 视频暂停播放。 |
| stopped  | string | 视频播放停止。 |
| error    | string | 错误状态。     |

## SeekMode<sup>8+</sup>

视频播放的Seek模式枚举,可通过seek方法作为参数传递下去。

| 名称              | 值   | 描述                                                         |
| ----------------- | ---- | ------------------------------------------------------------ |
| SEEK_NEXT_SYNC    | 0    | 表示跳转到指定时间点的下一个关键帧,建议向后快进的时候用这个枚举值 |
| SEEK_PREV_SYNC    | 1    | 表示跳转到指定时间点的上一个关键帧,建议向前快进的时候用这个枚举值 |
| SEEK_CLOSEST_SYNC | 2    | 表示跳转到指定时间点最近的关键帧。                           |
| SEEK_CLOSEST      | 3    | 表示精确跳转到指定时间点。                                   |

## PlaybackSpeed<sup>8+</sup>

视频播放的倍速枚举,可通过setSpeed方法作为参数传递下去。

| 名称                 | 值   | 描述                           |
| -------------------- | ---- | ------------------------------ |
| SPEED_FORWARD_0_75_X | 0    | 表示视频播放正常播速的0.75倍。 |
| SPEED_FORWARD_1_00_X | 1    | 表示视频播放正常播速。         |
| SPEED_FORWARD_1_25_X | 2    | 表示视频播放正常播速的1.25倍。 |
| SPEED_FORWARD_1_75_X | 3    | 表示视频播放正常播速的1.75倍。 |
| SPEED_FORWARD_2_00_X | 4    | 表示视频播放正常播速的2.00倍。 |

1500 1501 1502
## MediaDescription<sup>8+</sup>

### [key : string] : any
Z
zengyawen 已提交
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
通过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 已提交
1530 1531 1532

## AudioRecorder

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

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

### prepare<a name=audiorecorder_prepare></a>
Z
zengyawen 已提交
1538 1539 1540 1541 1542 1543 1544 1545 1546

prepare(config: AudioRecorderConfig): void

录音准备。

**参数:**

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

**示例:**

1551
```js
Z
zengyawen 已提交
1552
let audioRecorderConfig = {
1553
    audioEncoder : media.AudioEncoder.AAC_LC,
Z
zengyawen 已提交
1554 1555 1556
    audioEncodeBitRate : 22050,
    audioSampleRate : 22050,
    numberOfChannels : 2,
1557 1558 1559
    format : media.AudioOutputFormat.AAC_ADTS,
    uri : 'file:///data/accounts/account_0/appdata/appdata/recorder/test.m4a',       // 文件需先由调用者创建,并给予适当的权限
    location : { latitude : 30, longitude : 130},
Z
zengyawen 已提交
1560
}
1561 1562 1563
audioRecorder.on('prepare', () => {    //设置'prepare'事件回调
    console.log('prepare success');
});
B
bird_j 已提交
1564
audioRecorder.prepare(audioRecorderConfig);
Z
zengyawen 已提交
1565 1566 1567
```


1568
### start<a name=audiorecorder_start></a>
Z
zengyawen 已提交
1569 1570 1571

start(): void

B
bird_j 已提交
1572
开始录制,需在[prepare](#audiorecorder_on)事件成功触发后,才能调用start方法。
Z
zengyawen 已提交
1573 1574 1575

**示例:**

1576 1577 1578 1579 1580
```js
audioRecorder.on('start', () => {    //设置'start'事件回调
    console.log('audio recorder start success');
});
audioRecorder.start();
Z
zengyawen 已提交
1581
```
1582 1583 1584 1585 1586

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

pause():void

B
bird_j 已提交
1587
暂停录制,需要在[start](#audiorecorder_on)事件成功触发后,才能调用pause方法。
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601

**示例:**

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

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

resume():void

B
bird_j 已提交
1602
暂停录制,需要在[pause](#audiorecorder_on)事件成功触发后,才能调用resume方法。
1603 1604 1605 1606 1607 1608 1609 1610

**示例:**

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

1613
### stop<a name=audiorecorder_stop></a>
Z
zengyawen 已提交
1614 1615 1616 1617 1618 1619 1620

stop(): void

停止录音。

**示例:**

1621 1622 1623 1624 1625
```js
audioRecorder.on('stop', () => {    //设置'stop'事件回调
    console.log('audio recorder stop success');
});
audioRecorder.stop();
Z
zengyawen 已提交
1626 1627
```

1628
### release<a name=audiorecorder_release></a>
Z
zengyawen 已提交
1629 1630 1631 1632 1633 1634 1635

release(): void

释放录音资源。

**示例:**

1636
```js
B
bird_j 已提交
1637 1638 1639
audioRecorder.on('release', () => {    //设置'release'事件回调
    console.log('audio recorder release success');
});
1640 1641
audioRecorder.release();
audioRecorder = undefined;
Z
zengyawen 已提交
1642 1643
```

1644
### reset<a name=audiorecorder_reset></a>
Z
zengyawen 已提交
1645 1646 1647 1648 1649

reset(): void

重置录音。

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

**示例:**

B
bird_j 已提交
1654 1655 1656 1657 1658
```js
audioRecorder.on('reset', () => {    //设置'reset'事件回调
    console.log('audio recorder reset success');
});
audioRecorder.reset();
Z
zengyawen 已提交
1659 1660
```

B
bird_j 已提交
1661
### on('prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset')<a name=audiorecorder_on></a>
Z
zengyawen 已提交
1662

1663
on(type: 'prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset', callback: () => void): void
Z
zengyawen 已提交
1664 1665 1666 1667 1668 1669 1670

开始订阅音频录制事件。

**参数:**

| 参数名   | 类型     | 必填 | 说明                                                         |
| -------- | -------- | ---- | ------------------------------------------------------------ |
1671 1672
| 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 已提交
1673 1674 1675

**示例:**

1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
```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 已提交
1713
});
B
bird_j 已提交
1714
audioRecorder.prepare(audioRecorderConfig)       								// 设置录制参数 ,并触发'prepare'事件回调
Z
zengyawen 已提交
1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
```

### on('error')

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

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

**参数:**

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

1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
**示例:**

```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 已提交
1740 1741 1742 1743 1744

## AudioRecorderConfig

表示音频的录音配置。

1745 1746 1747 1748 1749 1750 1751 1752 1753
| 名称                  | 参数类型                                | 必填 | 说明                                                         |
| --------------------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| 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 已提交
1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767


## AudioEncoder

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

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


## AudioOutputFormat

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

Z
zengyawen 已提交
1769 1770 1771
| 名称     | 默认值 | 说明                                                         |
| -------- | ------ | ------------------------------------------------------------ |
| MPEG_4   | 2      | 封装为MPEG-4格式。                                           |
1772 1773 1774 1775
| AAC_ADTS | 6      | 封装为ADTS(Audio&nbsp;Data&nbsp;Transport&nbsp;Stream)格式,是AAC音频的传输流格式。 |

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

B
bird_j 已提交
1776
视频录制管理类,用于录制视频媒体。在调用VideoRecorder的方法前,需要先通过[createVideoRecorderAsync()](#media.createvideorecorderasync8)构建一个[VideoRecorder](#videorecorder8)实例。
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826

视频录制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 已提交
1827
let eventEmitter = new events.EventEmitter();                              
1828 1829 1830 1831

eventEmitter.on('prepare', () => {
    videoRecorder.prepare(videoConfig, (err) => {
        if (typeof (err) == 'undefined') {
B
bird_j 已提交
1832
            console.info('prepare success');
1833
        } else {
B
bird_j 已提交
1834
            console.info('prepare failed and error is ' + err.message);
1835 1836 1837 1838 1839 1840
        }
    });
});

media.createVideoRecorder((err, recorder) => {
    if (typeof (err) == 'undefined' && typeof (recorder) != 'undefined') {
B
bird_j 已提交
1841 1842 1843
        videoRecorder = recorder;
        console.info('createVideoRecorder success');
        eventEmitter.emit('prepare');                                        // prepare事件触发
1844
    } else {
B
bird_j 已提交
1845
        console.info('createVideoRecorder failed and error is ' + err.message);
1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936
    }
});
```

### 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 已提交
1937
let surfaceID = null;   											// 传递给外界的surfaceID
B
bird_j 已提交
1938 1939 1940
videoRecorder.getInputSurface((err, surfaceId) => {
    if (typeof (err) == 'undefined') {
        console.info('getInputSurface success');
B
bird_j 已提交
1941
        surfaceID = surfaceId;
B
bird_j 已提交
1942 1943 1944
    } else {
        console.info('getInputSurface failed and error is ' + err.message);
    }
1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967
});
```

### getInputSurface

getInputSurface(): Promise\<string>;

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

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

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

**返回值:**

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

**示例:**

```js
// promise
B
bird_j 已提交
1968 1969
let surfaceID = null;   											// 传递给外界的surfaceID
await videoRecorder.getInputSurface().then((surfaceId) => {
1970
    console.info('getInputSurface success');
B
bird_j 已提交
1971
    surfaceID = surfaceId;
1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996
}, (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 已提交
1997 1998 1999 2000 2001 2002
videoRecorder.start((err) => {
    if (typeof (err) == 'undefined') {
        console.info('start videorecorder success');
    } else {
        console.info('start videorecorder failed and error is ' + err.message);
    }
2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050
});
```

### 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 已提交
2051 2052 2053 2054 2055 2056
videoRecorder.pause((err) => {
    if (typeof (err) == 'undefined') {
        console.info('pause videorecorder success');
    } else {
        console.info('pause videorecorder failed and error is ' + err.message);
    }
2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102
});
```

### 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 已提交
2103 2104 2105 2106 2107 2108
videoRecorder.resume((err) => {
    if (typeof (err) == 'undefined') {
        console.info('resume videorecorder success');
    } else {
        console.info('resume videorecorder failed and error is ' + err.message);
    }
2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154
});
```

### 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 已提交
2155 2156 2157 2158 2159 2160
videoRecorder.stop((err) => {
    if (typeof (err) == 'undefined') {
        console.info('stop videorecorder success');
    } else {
        console.info('stop videorecorder failed and error is ' + err.message);
    }
2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206
});
```

### 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 已提交
2207 2208 2209 2210 2211 2212
videoRecorder.release((err) => {
    if (typeof (err) == 'undefined') {
        console.info('release videorecorder success');
    } else {
        console.info('release videorecorder failed and error is ' + err.message);
    }
2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258
});
```

### 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 已提交
2259 2260 2261 2262 2263 2264
videoRecorder.reset((err) => {
    if (typeof (err) == 'undefined') {
        console.info('reset videorecorder success');
    } else {
        console.info('reset videorecorder failed and error is ' + err.message);
    }
2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394
});
```

### 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   | 是   | 地理位置的经度。 |