使用投影上下文访问音频眼镜和显示眼镜上的硬件

适用的 XR 设备
本指南可帮助您为以下类型的 XR 设备打造优质体验。
音频和
显示眼镜

请求并获得必要权限后,您的应用便可以访问无屏眼镜或显示眼镜上的硬件。访问眼镜硬件(而非手机硬件)的关键在于使用投影上下文。

获取投影上下文主要有两种方式,具体取决于代码的执行位置:

如果您的代码在投影 activity 中运行,请获取投影上下文

如果应用的代码在投射的 activity 中运行,则其自己的 activity 上下文已经是投射的上下文。在这种情况下,在该 activity 中发出的调用已经可以访问眼镜的硬件。

获取在“电话”应用组件中运行的代码的投影上下文

如果应用中投影 activity 之外的部分(例如手机 activity 或服务)需要访问眼镜的硬件,则必须明确获取投影上下文。为此,请使用 createProjectedDeviceContext 方法:

@RequiresApi(Build.VERSION_CODES.BAKLAVA)
@OptIn(ExperimentalProjectedApi::class, ExperimentalCoroutinesApi::class)
private fun monitorProjectedConnectivity(activity: ComponentActivity) {
    activity.lifecycleScope.launch {
        // Before creating a projected context, check to see if the projected device is connected.
        // While this method returns true, the projected context remains valid.
        ProjectedContext.isProjectedDeviceConnected(activity, coroutineContext)
            .collectLatest { isConnected ->
                if (isConnected) {
                    // From a phone Activity or Service, get a context for the audio and display glasses.
                    // Re-initialize on reconnect: Obtain another context instance.
                    val projectedContext = try {
                        ProjectedContext.createProjectedDeviceContext(activity)
                    } catch (e: IllegalStateException) {
                        Log.e(TAG, "Failed to create projected context", e)
                        return@collectLatest
                    }

                    // Use the projectedContext to initialize system services (e.g., CameraManager).
                    Log.i(TAG, "Projected device connected. Initializing hardware...")
                } else {
                    // The projected context is destroyed when the device disconnects.
                    // Clean up on disconnect: Listen for 'false' and release resources.
                    Log.i(TAG, "Projected device disconnected. Cleaning up hardware resources...")
                }
            }
    }
}

检查有效性

将 createProjectedDeviceContext 调用封装在 ProjectedContext.isProjectedDeviceConnected 中。虽然此方法会返回 true,但投影上下文对已连接的设备仍然有效,并且您的“电话”应用 activity 或服务(例如 CameraManager)可以访问 AI 眼镜硬件。

断开连接时清理

投影上下文与已连接设备的生命周期相关联,因此会在设备断开连接时销毁。当设备断开连接时,ProjectedContext.isProjectedDeviceConnected 会返回 false。您的应用应监听此更改,并清理应用使用该投射上下文创建的所有系统服务(例如 CameraManager)或资源。

重新连接时重新初始化

眼镜重新连接后,您的应用可以使用 createProjectedDeviceContext 获取另一个投影上下文实例,然后使用新的投影上下文重新初始化任何系统服务或资源。

使用眼镜的麦克风录制音频

您可以使用蓝牙免提配置文件 (HFP) 通过眼镜录制音频。 在此模式下,眼镜使用标准耳机和高级音频分发配置文件 (A2DP) 配置文件连接到手机,其功能类似于典型的蓝牙外围设备。如果您的应用已设计为支持标准蓝牙录音,则您可以使用此方法从眼镜录制音频,而无需进行任何额外开发。

使用蓝牙 HFP 录制音频

如需使用蓝牙 HFP 录制音频,请先请求所需的运行时权限,然后使用 AudioManager API 录制音频,如以下部分所述。

请求权限

与任何标准蓝牙音频设备一样,RECORD_AUDIO、BLUETOOTH_CONNECT 和其他相关权限由手机控制,而不是由已连接的设备(例如无屏眼镜或带屏眼镜)控制。

请按照以下步骤请求权限:

  1. 在应用的清单文件中声明以下权限:

  2. 使用标准 Android 权限流程在运行时同时请求 RECORD_AUDIO 和 BLUETOOTH_CONNECT 权限。

使用 AudioManager 路由音频

在用户向您的应用授予必要的运行时权限后,请使用 AudioManager API 将通信设备设置为 TYPE_BLUETOOTH_SCO,以便通过蓝牙 HFP 路由音频。这会指示系统从蓝牙外围设备检索音频。

val audioManager = context.getSystemService(AudioManager::class.java) ?: return
val devices = audioManager.getDevices(AudioManager.GET_DEVICES_INPUTS)
val hfpDevice = devices.find { it.type == AudioDeviceInfo.TYPE_BLUETOOTH_SCO }

hfpDevice?.let { device ->
    val audioRecord = AudioRecord.Builder()
        .setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION)
        .setAudioFormat(audioFormat)
        .setBufferSizeInBytes(bufferSize)
        .build()

    // Route recording to the Bluetooth device
    audioRecord.setPreferredDevice(device)
    audioManager.setCommunicationDevice(device)

    audioRecord.startRecording()

使用眼镜的摄像头拍摄图片

如需使用眼镜的摄像头拍摄图片,请使用应用的正确上下文,设置 CameraX 的 ImageCapture 用例并将其绑定到眼镜的摄像头:

private fun startCameraOnGlasses(activity: ComponentActivity) {
    activity.lifecycleScope.launch {
        // Before creating a projected context, check to see if the projected device is connected.
        ProjectedContext.isProjectedDeviceConnected(activity, coroutineContext)
            .collectLatest { isConnected ->
                if (isConnected) {
                    // 1. Get the CameraProvider using the projected context.
                    // When using the projected context, DEFAULT_BACK_CAMERA maps to the audio and display glasses' camera.
                    val projectedContext = try {
                        ProjectedContext.createProjectedDeviceContext(activity)
                    } catch (e: IllegalStateException) {
                        Log.e(TAG, "Projected context could not be created", e)
                        return@collectLatest
                    }

                    val cameraProviderFuture = ProcessCameraProvider.getInstance(projectedContext)

                    cameraProviderFuture.addListener({
                        val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
                        val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA

                        // 2. Check for the presence of a camera.
                        if (!cameraProvider.hasCamera(cameraSelector)) {
                            Log.w(TAG, "The selected camera is not available.")
                            return@addListener
                        }

                        // 3. Query supported streaming resolutions using Camera2 Interop.
                        val cameraInfo = cameraProvider.getCameraInfo(cameraSelector)
                        val camera2CameraInfo = Camera2CameraInfo.from(cameraInfo)
                        val cameraCharacteristics = camera2CameraInfo.getCameraCharacteristic(
                            CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP
                        )

                        // 4. Define the resolution strategy.
                        val targetResolution = Size(1920, 1080)
                        val resolutionStrategy = ResolutionStrategy(
                            targetResolution,
                            ResolutionStrategy.FALLBACK_RULE_CLOSEST_LOWER
                        )
                        val resolutionSelector = ResolutionSelector.Builder()
                            .setResolutionStrategy(resolutionStrategy)
                            .build()

                        // 5. If you have other continuous use cases bound, such as Preview or ImageAnalysis,
                        // you can use  Camera2 Interop's CaptureRequestOptions to set the FPS
                        val fpsRange = Range(30, 60)
                        val captureRequestOptions = CaptureRequestOptions.Builder()
                            .setCaptureRequestOption(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, fpsRange)
                            .build()

                        // 6. Initialize the ImageCapture use case with options.
                        val imageCapture = ImageCapture.Builder()
                            // Optional: Configure resolution, format, etc.
                            .setResolutionSelector(resolutionSelector)
                            .build()

                        try {
                            // Unbind use cases before rebinding.
                            cameraProvider.unbindAll()

                            // Bind use cases to camera using the Activity as the LifecycleOwner.
                            cameraProvider.bindToLifecycle(
                                activity,
                                cameraSelector,
                                imageCapture
                            )
                        } catch (exc: Exception) {
                            Log.e(TAG, "Use case binding failed", exc)
                        }
                    }, ContextCompat.getMainExecutor(activity))
                }
            }
    }
}

代码要点

  • 使用投影设备上下文获取 ProcessCameraProvider 的实例。
  • 在投影上下文的范围内,选择摄像头时,眼镜的主朝外摄像头会映射到 DEFAULT_BACK_CAMERA。
  • 预绑定检查会使用 cameraProvider.hasCamera(cameraSelector) 验证所选摄像头在设备上是否可用,然后再继续。
  • 将 Camera2 互操作与 Camera2CameraInfo 搭配使用,以读取底层 CameraCharacteristics#SCALER_STREAM_CONFIGURATION_MAP,这对于对支持的分辨率进行高级检查非常有用。
  • 自定义 ResolutionSelector 旨在精确控制 ImageCapture 的输出图片分辨率。
  • 创建配置了自定义 ResolutionSelector 的 ImageCapture 用例。
  • 将 ImageCapture 用例绑定到 activity 的生命周期。这会根据 activity 的状态自动管理相机的打开和关闭(例如,在 activity 暂停时停止相机)。
  • 针对单流硬件进行配置:眼镜摄像头流水线一次只能有一个活跃流。单独绑定 ImageCapture 时,CameraX 默认会附加一个内部重复流 (MeteringRepeating) 用于对焦和测光,这会导致单流流水线停滞。如需单独绑定 ImageCapture 而不使用预览流,请通过在 CameraXConfig.Builder 上设置 setRepeatingStreamForced(false) 来停用强制重复流(例如,通过在 Application 类中实现 CameraXConfig.Provider 或在初始化之前配置 ProcessCameraProvider)。

设置好眼镜的摄像头后,您可以使用 CameraX 的 ImageCapture 类拍摄图片。如需了解如何使用 takePicture 拍摄图片,请参阅 CameraX 的文档。

使用眼镜的摄像头拍摄视频

如需使用眼镜的摄像头拍摄视频(而非图片),请将 ImageCapture 组件替换为相应的 VideoCapture 组件,并修改拍摄执行逻辑。

主要更改包括使用不同的用例、创建不同的输出文件,以及使用适当的视频录制方法启动捕获。 如需详细了解 VideoCapture API 及其使用方法,请参阅 CameraX 的视频拍摄文档。

下表显示了根据应用用例推荐的分辨率和帧速率:

使用场景 分辨率 帧速率
视频通信 1280x720 15 FPS
计算机视觉 640 x 480 10 FPS
AI 视频流式传输 640 x 480 1 FPS

从投影的 activity 访问手机的硬件

投射的 activity 还可以使用 createHostDeviceContext(context) 获取主机设备(手机)的上下文,从而访问手机的硬件(例如摄像头或麦克风):

@OptIn(ExperimentalProjectedApi::class)
private fun getPhoneContext(activity: ComponentActivity): Context? {
    return try {
        // From a projected Activity, get a context for the phone.
        ProjectedContext.createHostDeviceContext(activity)
    } catch (e: IllegalStateException) {
        Log.e(TAG, "Failed to create host device context", e)
        null
    }
}

在混合应用(同时包含移动设备和眼镜体验的应用)中访问主机设备(手机)特有的硬件或资源时,您必须明确选择正确的上下文,以确保应用可以访问正确的硬件: