RelayrtcDocs
Get started
Documentation
Build calls

Camera and microphone

Capture devices, show a local preview and distinguish mute from turning capture off.

On this page

Enable capture after joining a room, from a button the user controls. The participant token needs video:publish for camera video and audio:publish for microphone audio. Browser permission is also required; use HTTPS or localhost.

Render the examples below inside the provider and room from the quickstart.

Enable capture

camera.enable and microphone.enable capture and publish media. Catch errors where the user starts the operation so a denied permission or unavailable device produces useful feedback.

React
'use client'
 
import { useState } from 'react'
import { useLocalMedia, useLocalParticipant, useRoom } from '@relayrtc/react'
 
export function EnableDevices() {
  const local = useLocalParticipant()
  const { connectionState } = useRoom()
  const { camera, microphone } = useLocalMedia()
  const [error, setError] = useState<string | null>(null)
 
  async function enable(kind: 'camera' | 'microphone') {
    if (!local) return
    setError(null)
    try {
      if (kind === 'camera') {
        await local.camera.enable({
          width: { ideal: 1280 }, height: { ideal: 720 }, frameRate: { ideal: 30 },
        })
      } else {
        await local.microphone.enable({ echoCancellation: true, noiseSuppression: true })
      }
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : 'Unable to start the device')
    }
  }
 
  return (
    <div>
      <button disabled={!local || connectionState !== 'connected' || camera?.pending}
        onClick={() => void enable('camera')}>Enable camera</button>
      <button disabled={!local || connectionState !== 'connected' || microphone?.pending}
        onClick={() => void enable('microphone')}>Enable microphone</button>
      {error && <p role="alert">{error}</p>}
    </div>
  )
}

Capture constraints are requests to the browser. ideal allows fallback; exact can reject a device that cannot satisfy the constraint. Actual dimensions and frame rates depend on the device and browser.

Show your preview

Attach the local camera's MediaStreamTrack with useMediaTrack. Keep the preview muted to avoid local audio feedback.

React
'use client'
 
import { MediaLoader, useLocalMedia, useMediaTrack } from '@relayrtc/react'
 
export function CameraPreview() {
  const { camera } = useLocalMedia()
  const preview = useMediaTrack(camera?.track, { paused: camera?.muted ?? false })
 
  return (
    <div>
      <video ref={preview.ref} autoPlay muted playsInline hidden={!camera?.enabled || camera.muted} />
      {(!camera?.enabled || camera.muted) && <p>Camera off or paused</p>}
      {(camera?.pending || preview.isLoading) && <MediaLoader label="Starting camera" />}
      {preview.error && <p role="alert">{preview.error.message}</p>}
    </div>
  )
}

Camera off

Choose the operation that matches your interface:

OperationCapturePublication
await local.camera.mute()Stays openPaused after server confirmation; remote participants receive the paused state.
await local.camera.unmute()Stays openSending resumes after server confirmation.
await local.camera.disable()StopsRemoved from the room.
await local.camera.enable()StartsA camera publication becomes available.

Use disable for a camera-off action that releases the device. Await mute/unmute rather than treating the button click as confirmed state. For a remote camera, useMediaTrack(...).isPaused identifies a paused publication; when disabled, the track disappears from useTracks and your participant tile can show a placeholder.

Microphone mute

Microphone controls have the same distinction. mute() pauses sending while capture stays open; unmute() resumes it. disable() releases capture and removes the publication. Run these methods in an async handler and show any rejection.

Muted publications do not accrue active-media duration. Participant connection time is measured separately and can continue while all devices are muted. See usage.

Device selection

The following component lists available cameras and switches the active input. Device labels may be empty before permission has been granted.

React
'use client'
 
import { useState } from 'react'
import { useLocalParticipant, useRoom } from '@relayrtc/react'
import type { MediaInputDevice } from '@relayrtc/react'
 
export function CameraPicker() {
  const { room } = useRoom()
  const local = useLocalParticipant()
  const [cameras, setCameras] = useState<readonly MediaInputDevice[]>([])
  const [error, setError] = useState<string | null>(null)
 
  async function choose(deviceId?: string) {
    if (!room || !local) return
    setError(null)
    try {
      if (deviceId) await local.camera.switchDevice(deviceId)
      else setCameras((await room.devices.enumerate()).cameras)
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : 'Unable to change camera')
    }
  }
 
  return (
    <div>
      <button disabled={!room} onClick={() => void choose()}>List cameras</button>
      {cameras.map((camera, index) => (
        <button key={camera.deviceId} onClick={() => void choose(camera.deviceId)}>
          {camera.label || `Camera ${index + 1}`}
        </button>
      ))}
      {error && <p role="alert">{error}</p>}
    </div>
  )
}

Use the corresponding microphone list and microphone.switchDevice for audio inputs. For live device-change subscriptions and permission inspection, see devices and permissions.