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

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 {

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.

android:onClick="@{() -> viewModel.onToggleCamera()}"
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**](

Change Camera