• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Interface (PreviewOutput)
2<!--Kit: Camera Kit-->
3<!--Subsystem: Multimedia-->
4<!--Owner: @qano-->
5<!--SE: @leo_ysl-->
6<!--TSE: @xchaosioda-->
7
8> **NOTE**
9>
10> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
11
12PreviewOutput implements preview output. It inherits from [CameraOutput](arkts-apis-camera-CameraOutput.md).
13
14## Modules to Import
15
16```ts
17import { camera } from '@kit.CameraKit';
18```
19
20## on('frameStart')
21
22on(type: 'frameStart', callback: AsyncCallback\<void\>): void
23
24Subscribes to preview frame start events. This API uses an asynchronous callback to return the result.
25
26> **NOTE**
27>
28> Currently, you cannot use **off()** to unregister the callback in the callback method of **on()**.
29
30**Atomic service API**: This API can be used in atomic services since API version 19.
31
32**System capability**: SystemCapability.Multimedia.Camera.Core
33
34**Parameters**
35
36| Name     | Type                 | Mandatory| Description                                    |
37| -------- | -------------------- | ---- | --------------------------------------- |
38| type     | string               | Yes  | Event type. The value is fixed at **'frameStart'**. The event can be listened for when a previewOutput instance is created. This event is triggered and returned when the bottom layer starts exposure for the first time.|
39| callback | AsyncCallback\<void\> | Yes  | Callback used to return the result. The preview starts as long as this event is returned.                   |
40
41**Example**
42
43```ts
44import { BusinessError } from '@kit.BasicServicesKit';
45
46function callback(err: BusinessError): void {
47  if (err !== undefined && err.code !== 0) {
48    console.error(`Callback Error, errorCode: ${err.code}`);
49    return;
50  }
51  console.info('Preview frame started');
52}
53
54function registerPreviewOutputFrameStart(previewOutput: camera.PreviewOutput): void {
55  previewOutput.on('frameStart', callback);
56}
57```
58
59## off('frameStart')
60
61off(type: 'frameStart', callback?: AsyncCallback\<void\>): void
62
63Unsubscribes from preview frame start events.
64
65**Atomic service API**: This API can be used in atomic services since API version 19.
66
67**System capability**: SystemCapability.Multimedia.Camera.Core
68
69**Parameters**
70
71| Name     | Type                 | Mandatory| Description                                    |
72| -------- | -------------------- | ---- | --------------------------------------- |
73| type     | string               | Yes  | Event type. The value is fixed at **'frameStart'**. The event can be listened for when a previewOutput instance is created.|
74| callback | AsyncCallback\<void\> | No  | Callback used to return the result. If this parameter is specified, the subscription to the specified event with the specified callback is canceled. (The callback object cannot be an anonymous function.) Otherwise, the subscriptions to the specified event with all the callbacks are canceled.|
75
76**Example**
77
78```ts
79function unregisterPreviewOutputFrameStart(previewOutput: camera.PreviewOutput): void {
80  previewOutput.off('frameStart');
81}
82```
83
84## on('frameEnd')
85
86on(type: 'frameEnd', callback: AsyncCallback\<void\>): void
87
88Subscribes to preview frame end events. This API uses an asynchronous callback to return the result.
89
90> **NOTE**
91>
92> Currently, you cannot use **off()** to unregister the callback in the callback method of **on()**.
93
94**Atomic service API**: This API can be used in atomic services since API version 19.
95
96**System capability**: SystemCapability.Multimedia.Camera.Core
97
98**Parameters**
99
100| Name     | Type                 | Mandatory| Description                                 |
101| -------- | -------------------- | ---- | ------------------------------------- |
102| type     | string               | Yes  | Event type. The value is fixed at **'frameEnd'**. The event can be listened for when a previewOutput instance is created. This event is triggered and returned when the last frame of preview ends.|
103| callback | AsyncCallback\<void\> | Yes  | Callback used to return the result. The preview ends as long as this event is returned.               |
104
105**Example**
106
107```ts
108import { BusinessError } from '@kit.BasicServicesKit';
109
110function callback(err: BusinessError): void {
111  if (err !== undefined && err.code !== 0) {
112    console.error(`Callback Error, errorCode: ${err.code}`);
113    return;
114  }
115  console.info('Preview frame ended');
116}
117
118function registerPreviewOutputFrameEnd(previewOutput: camera.PreviewOutput): void {
119  previewOutput.on('frameEnd', callback);
120}
121```
122
123## off('frameEnd')
124
125off(type: 'frameEnd', callback?: AsyncCallback\<void\>): void
126
127Unsubscribes from preview frame end events.
128
129**Atomic service API**: This API can be used in atomic services since API version 19.
130
131**System capability**: SystemCapability.Multimedia.Camera.Core
132
133**Parameters**
134
135| Name     | Type                 | Mandatory| Description                                 |
136| -------- | -------------------- | ---- | ------------------------------------- |
137| type     | string               | Yes  | Event type. The value is fixed at **'frameEnd'**. The event can be listened for when a previewOutput instance is created.|
138| callback | AsyncCallback\<void\> | No  | Callback used to return the result. If this parameter is specified, the subscription to the specified event with the specified callback is canceled. (The callback object cannot be an anonymous function.) Otherwise, the subscriptions to the specified event with all the callbacks are canceled.|
139
140**Example**
141
142```ts
143function unregisterPreviewOutputFrameEnd(previewOutput: camera.PreviewOutput): void {
144  previewOutput.off('frameEnd');
145}
146```
147
148## on('error')
149
150on(type: 'error', callback: ErrorCallback): void
151
152Subscribes to PreviewOutput error events. This API uses an asynchronous callback to return the result.
153
154> **NOTE**
155>
156> Currently, you cannot use **off()** to unregister the callback in the callback method of **on()**.
157
158**Atomic service API**: This API can be used in atomic services since API version 19.
159
160**System capability**: SystemCapability.Multimedia.Camera.Core
161
162**Parameters**
163
164| Name    | Type        | Mandatory| Description                      |
165| -------- | --------------| ---- | ------------------------ |
166| type     | string        | Yes  | Event type. The value is fixed at **'error'**. The event can be listened for when a previewOutput instance is created. This event is triggered and the corresponding error message is returned when an error occurs during the use of a preview-related API such as [Session.start](arkts-apis-camera-Session.md#start11-1) or [CameraOutput.release](arkts-apis-camera-CameraOutput.md#release-1).|
167| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes  | Callback used to return an error code defined in [CameraErrorCode](arkts-apis-camera-e.md#cameraerrorcode). |
168
169**Example**
170
171```ts
172import { BusinessError } from '@kit.BasicServicesKit';
173
174function callback(previewOutputError: BusinessError): void {
175  console.error(`Preview output error code: ${previewOutputError.code}`);
176}
177
178function registerPreviewOutputError(previewOutput: camera.PreviewOutput): void {
179  previewOutput.on('error', callback)
180}
181```
182
183## off('error')
184
185off(type: 'error', callback?: ErrorCallback): void
186
187Unsubscribes from PreviewOutput error events.
188
189**Atomic service API**: This API can be used in atomic services since API version 19.
190
191**System capability**: SystemCapability.Multimedia.Camera.Core
192
193**Parameters**
194
195| Name    | Type        | Mandatory| Description                      |
196| -------- | --------------| ---- | ------------------------ |
197| type     | string        | Yes  | Event type. The value is fixed at **'error'**. The event can be listened for when a previewOutput instance is created.|
198| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | No  | Callback used to return the result. If this parameter is specified, the subscription to the specified event with the specified callback is canceled. (The callback object cannot be an anonymous function.) Otherwise, the subscriptions to the specified event with all the callbacks are canceled.|
199
200**Example**
201
202```ts
203function unregisterPreviewOutputError(previewOutput: camera.PreviewOutput): void {
204  previewOutput.off('error');
205}
206```
207
208## getSupportedFrameRates<sup>12+</sup>
209
210 getSupportedFrameRates(): Array\<FrameRateRange\>
211
212Obtains the supported frame rates.
213
214**Atomic service API**: This API can be used in atomic services since API version 19.
215
216**System capability**: SystemCapability.Multimedia.Camera.Core
217
218**Return value**
219
220|      Type     |     Description    |
221| -------------  | ------------ |
222| Array<[FrameRateRange](arkts-apis-camera-i.md#frameraterange)> | Array of supported frame rates.|
223
224**Example**
225
226```ts
227function getSupportedFrameRates(previewOutput: camera.PreviewOutput): Array<camera.FrameRateRange> {
228  let supportedFrameRatesArray: Array<camera.FrameRateRange> = previewOutput.getSupportedFrameRates();
229  return supportedFrameRatesArray;
230}
231```
232
233## setFrameRate<sup>12+</sup>
234
235setFrameRate(minFps: number, maxFps: number): void
236
237Sets a frame rate range for preview streams. The range must be within the supported frame rate range, which can be obtained by calling [getSupportedFrameRates](#getsupportedframerates12).
238
239> **NOTE**
240>
241> This API is valid only in [PhotoSession](arkts-apis-camera-PhotoSession.md) or [VideoSession](arkts-apis-camera-VideoSession.md) mode.
242
243**Atomic service API**: This API can be used in atomic services since API version 19.
244
245**System capability**: SystemCapability.Multimedia.Camera.Core
246
247**Parameters**
248
249| Name    | Type        | Mandatory| Description                      |
250| -------- | --------------| ---- | ------------------------ |
251| minFps   | number        | Yes  | Minimum frame rate, in fps.|
252| maxFps   | number        | Yes  | Maximum frame rate, in fps. When the minimum value is greater than the maximum value, the API does not take effect.|
253
254**Error codes**
255
256For details about the error codes, see [Camera Error Codes](errorcode-camera.md).
257
258| ID       | Error Message       |
259| --------------- | --------------- |
260| 7400101                |  Parameter missing or parameter type incorrect.        |
261| 7400110                |  Unresolved conflicts with current configurations.     |
262
263**Example**
264
265```ts
266function setFrameRateRange(previewOutput: camera.PreviewOutput, frameRateRange: Array<number>): void {
267  previewOutput.setFrameRate(frameRateRange[0], frameRateRange[1]);
268}
269```
270
271## getActiveFrameRate<sup>12+</sup>
272
273getActiveFrameRate(): FrameRateRange
274
275Obtains the configured frame rate range.
276
277This API is valid only after [setFrameRate](#setframerate12) is called to set a frame rate range for preview streams.
278
279**Atomic service API**: This API can be used in atomic services since API version 19.
280
281**System capability**: SystemCapability.Multimedia.Camera.Core
282
283**Return value**
284
285|      Type     |     Description    |
286| -------------  | ------------ |
287| [FrameRateRange](arkts-apis-camera-i.md#frameraterange) | Frame rate range.|
288
289**Example**
290
291```ts
292function getActiveFrameRate(previewOutput: camera.PreviewOutput): camera.FrameRateRange {
293  let activeFrameRate: camera.FrameRateRange = previewOutput.getActiveFrameRate();
294  return activeFrameRate;
295}
296```
297
298## getActiveProfile<sup>12+</sup>
299
300getActiveProfile(): Profile
301
302Obtains the profile that takes effect currently.
303
304**Atomic service API**: This API can be used in atomic services since API version 19.
305
306**System capability**: SystemCapability.Multimedia.Camera.Core
307
308**Return value**
309
310|      Type     | Description       |
311| -------------  |-----------|
312| [Profile](arkts-apis-camera-i.md#profile) | Profile obtained.|
313
314**Error codes**
315
316For details about the error codes, see [Camera Error Codes](errorcode-camera.md).
317
318| ID  | Error Message                        |
319|---------|------------------------------|
320| 7400201 | Camera service fatal error.  |
321
322**Example**
323
324```ts
325import { BusinessError } from '@kit.BasicServicesKit';
326
327function testGetActiveProfile(previewOutput: camera.PreviewOutput): camera.Profile | undefined {
328  let activeProfile: camera.Profile | undefined = undefined;
329  try {
330    activeProfile = previewOutput.getActiveProfile();
331  } catch (error) {
332    // If the operation fails, error.code is returned and processed.
333    let err = error as BusinessError;
334    console.error(`The previewOutput.getActiveProfile call failed. error code: ${err.code}`);
335  }
336  return activeProfile;
337}
338```
339
340## getPreviewRotation<sup>12+</sup>
341
342getPreviewRotation(displayRotation: number): ImageRotation
343
344Obtains the preview rotation degree.
345
346- Device' natural orientation: The default orientation of the device (phone) is in portrait mode, with the charging port facing downward.
347- Camera lens angle: equivalent to the angle at which the camera is rotated clockwise to match the device's natural direction. The rear camera sensor of a phone is installed in landscape mode. Therefore, it needs to be rotated by 90 degrees clockwise to match the device's natural direction.
348- Screen orientation: The upper left corner of the image displayed on the screen is the first pixel, which is the coordinate origin. In the case of lock screen, the direction is the same as the device's natural orientation.
349
350**Atomic service API**: This API can be used in atomic services since API version 19.
351
352**System capability**: SystemCapability.Multimedia.Camera.Core
353
354**Parameters**
355
356| Name    | Type        | Mandatory| Description                      |
357| -------- | --------------| ---- | ------------------------ |
358| displayRotation | number  | Yes  | Screen rotation angle of the display. It is obtained by calling [display.getDefaultDisplaySync](../apis-arkui/js-apis-display.md#displaygetdefaultdisplaysync9).|
359
360**Return value**
361
362|      Type     | Description       |
363| -------------  |-----------|
364| [ImageRotation](arkts-apis-camera-e.md#imagerotation) | Preview rotation degree.|
365
366**Error codes**
367
368For details about the error codes, see [Camera Error Codes](errorcode-camera.md).
369
370| ID  | Error Message                        |
371|---------|------------------------------|
372| 7400101 | Parameter missing or parameter type incorrect.  |
373| 7400201 | Camera service fatal error.  |
374
375**Example**
376
377```ts
378import { BusinessError } from '@kit.BasicServicesKit';
379
380function testGetPreviewRotation(previewOutput: camera.PreviewOutput, imageRotation : camera.ImageRotation): camera.ImageRotation {
381  let previewRotation: camera.ImageRotation = camera.ImageRotation.ROTATION_0;
382  try {
383    previewRotation = previewOutput.getPreviewRotation(imageRotation);
384    console.log(`Preview rotation is: ${previewRotation}`);
385  } catch (error) {
386    // If the operation fails, error.code is returned and processed.
387    let err = error as BusinessError;
388    console.error(`The previewOutput.getPreviewRotation call failed. error code: ${err.code}`);
389  }
390  return previewRotation;
391}
392```
393
394## setPreviewRotation<sup>12+</sup>
395
396setPreviewRotation(previewRotation: ImageRotation, isDisplayLocked?: boolean): void
397
398Sets the preview rotation degree.
399
400**Atomic service API**: This API can be used in atomic services since API version 19.
401
402**System capability**: SystemCapability.Multimedia.Camera.Core
403
404**Parameters**
405
406| Name    | Type        | Mandatory| Description                      |
407| -------- | --------------| ---- | ------------------------ |
408| previewRotation | [ImageRotation](arkts-apis-camera-e.md#imagerotation)  | Yes  | Preview rotation angle.|
409| isDisplayLocked | boolean  | No  | Whether the display is locked.|
410
411**Error codes**
412
413For details about the error codes, see [Camera Error Codes](errorcode-camera.md).
414
415| ID  | Error Message                        |
416|---------|------------------------------|
417| 7400101 | Parameter missing or parameter type incorrect.  |
418| 7400201 | Camera service fatal error.  |
419
420**Example**
421
422```ts
423import { BusinessError } from '@kit.BasicServicesKit';
424
425function testSetPreviewRotation(previewOutput: camera.PreviewOutput, previewRotation : camera.ImageRotation, isDisplayLocked: boolean): void {
426  try {
427    previewOutput.setPreviewRotation(previewRotation, isDisplayLocked);
428  } catch (error) {
429    // If the operation fails, error.code is returned and processed.
430    let err = error as BusinessError;
431    console.error(`The previewOutput.setPreviewRotation call failed. error code: ${err.code}`);
432  }
433  return;
434}
435```
436
437
438## start<sup>(deprecated)</sup>
439
440start(callback: AsyncCallback\<void\>): void
441
442Starts to output preview streams. This API uses an asynchronous callback to return the result.
443
444> **NOTE**
445>
446> This API is supported since API version 10 and deprecated since API version 11. You are advised to use [Session.start](arkts-apis-camera-Session.md#start11) instead.
447
448**System capability**: SystemCapability.Multimedia.Camera.Core
449
450**Parameters**
451
452| Name     | Type                 | Mandatory| Description                |
453| -------- | -------------------- | ---- | -------------------- |
454| callback | AsyncCallback\<void\> | Yes  | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](arkts-apis-camera-e.md#cameraerrorcode) is returned.|
455
456**Error codes**
457
458For details about the error codes, see [Camera Error Codes](errorcode-camera.md).
459
460| ID        | Error Message       |
461| --------------- | --------------- |
462| 7400103                |  Session not config.                                   |
463
464**Example**
465
466```ts
467import { BusinessError } from '@kit.BasicServicesKit';
468
469function startPreviewOutput(previewOutput: camera.PreviewOutput): void {
470  previewOutput.start((err: BusinessError) => {
471    if (err) {
472      console.error(`Failed to start the preview output, error code: ${err.code}.`);
473      return;
474    }
475    console.info('Callback returned with preview output started.');
476  });
477}
478```
479
480## start<sup>(deprecated)</sup>
481
482start(): Promise\<void\>
483
484Starts to output preview streams. This API uses a promise to return the result.
485
486> **NOTE**
487>
488> This API is supported since API version 10 and deprecated since API version 11. You are advised to use [Session.start](arkts-apis-camera-Session.md#start11-1) instead.
489
490**System capability**: SystemCapability.Multimedia.Camera.Core
491
492**Return value**
493
494| Type           | Description               |
495| -------------- |-------------------|
496| Promise\<void\> | Promise that returns no value. |
497
498**Error codes**
499
500For details about the error codes, see [Camera Error Codes](errorcode-camera.md).
501
502| ID        | Error Message       |
503| --------------- | --------------- |
504| 7400103                |  Session not config.                                   |
505
506**Example**
507
508```ts
509import { BusinessError } from '@kit.BasicServicesKit';
510
511function startPreviewOutput(previewOutput: camera.PreviewOutput): void {
512  previewOutput.start().then(() => {
513    console.info('Promise returned with preview output started.');
514  }).catch((error: BusinessError) => {
515    console.error(`Failed to preview output start, error code: ${error.code}.`);
516  });
517}
518```
519
520## stop<sup>(deprecated)</sup>
521
522stop(callback: AsyncCallback\<void\>): void
523
524Stops outputting preview streams. This API uses an asynchronous callback to return the result.
525
526> **NOTE**
527>
528> This API is supported since API version 10 and deprecated since API version 11. You are advised to use [Session.stop](arkts-apis-camera-Session.md#stop11) instead.
529
530**System capability**: SystemCapability.Multimedia.Camera.Core
531
532**Parameters**
533
534| Name     | Type                 | Mandatory| Description                |
535| -------- | -------------------- | ---- | -------------------- |
536| callback | AsyncCallback\<void\> | Yes  | Callback used to return the result.|
537
538**Example**
539
540```ts
541import { BusinessError } from '@kit.BasicServicesKit';
542
543function stopPreviewOutput(previewOutput: camera.PreviewOutput): void {
544  previewOutput.stop((err: BusinessError) => {
545    if (err) {
546      console.error(`Failed to stop the preview output, error code: ${err.code}.`);
547      return;
548    }
549    console.info('Returned with preview output stopped.');
550  })
551}
552```
553
554## stop<sup>(deprecated)</sup>
555
556stop(): Promise\<void\>
557
558Stops outputting preview streams. This API uses a promise to return the result.
559
560> **NOTE**
561>
562> This API is supported since API version 10 and deprecated since API version 11. You are advised to use [Session.stop](arkts-apis-camera-Session.md#stop11-1) instead.
563
564**System capability**: SystemCapability.Multimedia.Camera.Core
565
566**Return value**
567
568| Type           | Description                    |
569| -------------- | ------------------------ |
570| Promise\<void\> | Promise that returns no value.|
571
572**Example**
573
574```ts
575import { BusinessError } from '@kit.BasicServicesKit';
576
577function stopPreviewOutput(previewOutput: camera.PreviewOutput): void {
578  previewOutput.stop().then(() => {
579    console.info('Callback returned with preview output stopped.');
580  }).catch((error: BusinessError) => {
581    console.error(`Failed to preview output stop, error code: ${error.code}.`);
582  });
583}
584```
585