Skip to main content

Change camera

Until now we only used the front camera. In this tutorial you will add a new button to toggle between the front and back camera.

Change Camera Button

If you want, you can download the initial code from Step.04-Exercise-Change-camera.

Modify the conference ViewModel

The first step is to define the LiveData that will store the current camera status:

// Notify whether the back camera is select or the front camera
private val _isBackCamera = MutableLiveData<Boolean>()
val isBackCamera: LiveData<Boolean>
get() = _isBackCamera

Now we define the method that will be called when we push the toggle camera button. This method will trigger the function switchCamera which has as callback function as an input parameter. If it's a success, we will change the value of the LiveData .

fun onToggleCamera() {
val callback = object : CameraVideoTrack.SwitchCameraCallback {
override fun onFailure(error: String) {}
override fun onSuccess(front: Boolean) {
_isBackCamera.value = !front
}
}
_localVideoTrack.value?.switchCamera(callback)
}

Modify the conference fragment

Once we have finished with the ViewModel , we will make a modification to the ConferenceFragment . In this case, we will observe the LiveData that we have defined in a previous step and flip our localVideoSurface accordingly.

private fun setVideoObservers() {
...
viewModel.isBackCamera.observe(viewLifecycleOwner, Observer {
binding.localVideoSurface.setMirror(!it)
})
})

Modify the conference layout

The last step is to modify the layout to add a new button in our interface that will change the camera.

<com.google.android.material.button.MaterialButton
android:id="@+id/change_camera_button"
android:layout_width="60dp"
android:layout_height="72dp"
android:layout_margin="4dp"
android:backgroundTint="@color/teal"
android:onClick="@{() -> viewModel.onToggleCamera()}"
app:cornerRadius="100dp"
app:enabled="@{viewModel.isBackCamera}"
app:icon="@drawable/camera_switch"
app:iconGravity="textStart"
app:iconPadding="0dp"
app:iconSize="30dp" />

Run the app

After these small modifications, you can push button to change to the back camera. You will also notice that the video of your front camera is mirrored, while the video of the back camera is not.

You can compare your code with the solution in Step.04-Solution-Change-camera.** You can also check the differences with the previous tutorial in the [git diff**](https://github.com/pexip/pexip-tutorial-android/compare/Step.03-Solution-Mute-audio-and-video...Step.04-Solution-Change-camera).

Change Camera