For AI agents: the complete documentation index is available at /apps-plugin/docs/llms.txt, the full documentation bundle is available at /apps-plugin/docs/llms-full.txt, and this page is available as Markdown at /apps-plugin/docs/components/media/camera.md.

camera

相机预览与拍摄组件,提供拍照和录像能力。

扫码预览

扫码预览 camera

Props

属性名类型默认值必填说明
classNamestring-否组件的类名。
devicePositionCameraDevicePosition'front'否该实例持有采集会话时使用的摄像头朝向。
onError(event: CameraError) => void-否权限、配置、拍照、录像或临时文件错误时触发。
onReady() => void-否采集会话和预览启动后触发。
refRef<CameraRef>-否用于调用拍照和录像的实例方法。
styleCSSProperties-否组件的样式,默认尺寸为 100% × 240px。

Ref 方法

方法名类型说明
requestFocus() => Promise<void>抢占共享的原生采集会话,并按当前实例的 devicePosition 更新预览。
仅前台页面的实例可以调用,后台页面调用会失败。
startRecord() => Promise<void>开始录制视频,需要相机和麦克风权限。
stopRecord() => Promise<CameraCaptureResult>停止录制,在文件写入完成后返回临时文件路径。
takePhoto() => Promise<CameraCaptureResult>拍摄一张 JPEG 照片,返回临时文件路径。

前端库版本不低于 0.2.0。

基本用法

import { useRef, useState } from '@byted-doubao-apps/framework';
import type { CameraRef } from '@byted-doubao-apps/framework/components';

export default function CameraPage() {
  const cameraRef = useRef<CameraRef>(null);
  const [photoPath, setPhotoPath] = useState('');

  return (
    <view>
      <camera
        ref={cameraRef}
        devicePosition="front"
        style={{ width: '100%', height: '320px' }}
        onError={(error) => console.error(error.errCode, error.errMessage)}
      />
      <button text="激活相机" onClick={() => cameraRef.current?.requestFocus()} />
      <button
        text="拍照"
        onClick={async () => {
          const result = await cameraRef.current?.takePhoto();
          if (result) setPhotoPath(result.path);
        }}
      />
      {photoPath ? <image src={photoPath} mode="aspectFit" /> : null}
    </view>
  );
}

共享采集会话与焦点

全局共享一个原生采集会话和预览层,只有前台 AppletFullPageContainer 中的实例可以获得 焦点,同页后创建的实例默认抢占。

  • 页面隐藏时解绑预览;没有前台相机时停止采集。返回页面后自动恢复该页最近获得焦点的实例, 并触发 onReady。
  • 后台页面调用 requestFocus() 会失败。切页或同页抢占会结束原实例的录制,被抢占的实例 会收到 onError 并停止预览。
  • 收到 onReady 后再拍照或录像;失焦的实例可以调用 requestFocus() 重新抢占,然后等待 onReady。
  • 非焦点实例修改 devicePosition 只保存自身设置,在该实例下次获得焦点时生效。
  • 录像期间不能切换前后摄像头。

临时文件

takePhoto 和 stopRecord 返回的 path 是 appletfile://temp/... 虚拟路径。临时文件位于 当前应用插件隔离的缓存目录,在退出时清理;如需长期保存,用 getFileSystemManager().saveFile({ tempFilePath: path }) 转存到用户目录 appletfile://user/...,保存后的路径由返回值的 savedFilePath 给出。

错误码

errCode含义
1状态不允许,例如相机未 ready、重复开始或停止录像
2相机或麦克风权限被拒绝
3摄像头或麦克风不可用
4采集会话或输入输出配置失败
5拍照失败
6录像失败或意外中断
7临时文件路径创建或写入失败

注意事项

  • 授权分两层。应用级:需要在 manifest 的 permissions 中声明 scope.camera,录像还要 声明 scope.record,未声明时校验不通过。系统级:由客户端弹窗向用户申请,拍照只申请 相机权限,录像会同时申请相机和麦克风权限。
  • 任一层未通过都通过 onError 返回 errCode: 2,需要据此引导用户到系统设置开启。
  • Web 模拟器不渲染相机画面,ref 上的方法也不可用,需要在真机验收。