You need to enable JavaScript to run this app.
导航

切换摄像头

最近更新时间2024.03.26 11:13:46

首次发布时间2023.11.21 14:51:30

你可以使用 session.switchVideoSource 这个方法来切换摄像头或者使用视频文件作为 Web AR SDK 的输入。

// 使用前置摄像头
// Use front facing camera
await session.switchVideoSource({
    type: "camera",
    facingMode: "user"
});

// 使用后置摄像头
// Use back facing camera
await session.switchVideoSource({
    type: "camera",
    facingMode: "environment"
});

来回切换前后置摄像头

你可以通过 session.videoSource 属性来获取当前设置的视频源,并根据当前摄像头朝向选择要切换到的方向。

import { CameraFacingMode } from "@volcengine/webar";

const toggleCamera = async () => {
    let targetFacingMode: CameraFacingMode;
    if (session.videoSource.type === "camera") {
        targetFacingMode = session.videoSource.facingMode === "user" ? "environment" : "user";
    } else {
        targetFacingMode = "user";
    }
    await session.switchVideoSource({
        type: "camera",
        facingMode: targetFacingMode,
    });
};

默认摄像头

你可以在初始化 ARSession 的时候就指定 videoSource 参数,来设置默认使用的摄像头。

const session = ARSDK.createSession({
    canvas,
    authorization: { ... },
    videoSource: {
        type: "camera",
        // 可选 user: 前置; environment:后置;
        // Avaliable options: user / environment
        facingMode: "user"
    }
});

使用视频文件或视频流

你也可以使用视频文件或视频流作为 ARSession 的视频源。

// 使用媒体流作为输入
// Use a MediaStream object.
await session.switchVideoSource({
    type: "video-stream",
    stream: mediaStreamObject
});

// 使用视频文件作为输入
// Use a video file
await session.switchVideoSource({
    type: "video-url",
    url: videoURLString
});

使用图片

从 3.9.0 版本开始可用
你还可以使用图片作为 ARSession 的输入源。

// 使用图片文件
// Use an image file.
await session.switchVideoSource({
    type: "image-file",
    file: blob
});

// 使用图片地址
// Use an image URL.
await session.switchVideoSource({
    type: "image-url",
    url: imageURL
});