Languages
[Edit]
EN

React - list available audio and video input devices (e.g. web cameras and microphones)

3 points
Created by:
ArcadeParade
666

In this short article, we would like to show how using React in simple way list available input audio and input video devices (web cameras and microphones).

1. Practical example

In this section, you can find reusable logic that lists available input devices.

Devices are ordered by importance. It means the most recommended or default devices should be listed as first.

// ONLINE-RUNNER:browser;

// import React from 'react';

const listDevices = async () => {
    const devices = await navigator.mediaDevices?.enumerateDevices?.();
    if (devices) {
        const video = [];
        const audio = [];
        for (const device of devices) {
            switch (device.kind) {
                case 'videoinput':
                    video.push(device);
                    break;
                case 'audioinput':
                    audio.push(device);
                    break;
            }
        }
        return { video, audio };
    } else {
        throw new Error('No support for multimedia devices.');
    }
};


// Usage example:

const App = () => {
    const [error, setError] = React.useState(null);
    const [devices, setDevices] = React.useState(null);
    React.useEffect(() => {
        const promise = listDevices();  // <--- lists available input audio and input video devices
        promise
          .then((devices) => setDevices(devices))
          .catch((error) => setError(error));
      ;
    }, []);
    return (
        <div>
          {error && (<div>{error}</div>)}
          {devices && (
            <>
              {devices.video.length === 0 && (<div>Video devices: not detected!</div>)}
              {devices.video.length > 0 && (
                <>
                  <div>Video devices:</div>
                  <ul>
                    {devices.video.map((videoDevice) => (
                      <li key={videoDevice.deviceId}>
                        <div>deviceId: {videoDevice.deviceId}</div>
                        <div>kind: {videoDevice.kind}</div>
                        <div>label: {videoDevice.label}</div>
                        <div>groupId: {videoDevice.groupId}</div>
                      </li>
                    ))}
                  </ul>
                </>
              )}
              {devices.audio.length === 0 && (<div>Audio devices: not detected!</div>)}
              {devices.audio.length > 0 && (
                <>
                  <div>Audio devices:</div>
                  <ul>
                    {devices.video.map((audioDevice) => (
                      <li key={audioDevice.deviceId}>
                        <div>deviceId: {audioDevice.deviceId}</div>
                        <div>kind: {audioDevice.kind}</div>
                        <div>label: {audioDevice.label}</div>
                        <div>groupId: {audioDevice.groupId}</div>
                      </li>
                    ))}
                  </ul>
                </>
              )}
              </>
          )}
        </div>
    );
};

// export default App;

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);

2. Selecting video/audio device example

In this example, we present listing available audio and video input devices with the possibility of choosing them in the select box.

// ONLINE-RUNNER:browser;

// import React from 'react';

const listDevices = async () => {
    const devices = await navigator.mediaDevices?.enumerateDevices?.();
    if (devices) {
        const video = [];
        const audio = [];
        for (const device of devices) {
            switch (device.kind) {
                case 'videoinput':
                    video.push(device);
                    break;
                case 'audioinput':
                    audio.push(device);
                    break;
            }
        }
        return { video, audio };
    } else {
        throw new Error('No support for multimedia devices.');
    }
};


// Usage example:

const fieldStyle = {
    display: 'flex'
};

const labelStyle = {
    flex: '0 110px'
};

const selectStyle = {
    flex: 'auto'
};

const App = () => {
    const [error, setError] = React.useState(null);
    const [devices, setDevices] = React.useState(null);
    React.useEffect(() => {
        const promise = listDevices();  // <--- lists available input audio and input video devices
        promise
          .then((devices) => setDevices(devices))
          .catch((error) => setError(error));
      ;
    }, []);
    const handleVideoDeviceChange = (e) => {
        const device = devices.video[e.target.value];
        console.log(`Video device change:\n  label: ${device.label}\n  deviceId: ${device.deviceId}\n  groupId: ${device.groupId}`);
    };
    const handleAudioDeviceChange = (e) => {
        const device = devices.audio[e.target.value];
        console.log(`Audio device change:\n  label: ${device.label}\n  deviceId: ${device.deviceId}\n  groupId: ${device.groupId}`);
    };
    return (
        <div>
          {error && (<div>{error}</div>)}
          {devices && (
            <>
              <label style={fieldStyle}>
                <span style={labelStyle}>Video device: </span>
                <select style={selectStyle} disabled={devices.video.length === 0} onChange={handleVideoDeviceChange}>
                  {devices.video.map((device, index) => (
                      <option key={device.deviceId} value={index}>
                        {device.label || device.deviceId || device.groupId}
                      </option>
                  ))}
                </select>
              </label>
              <label style={fieldStyle}>
                <span style={labelStyle}>Audio device: </span>
                <select style={selectStyle} disabled={devices.audio.length === 0} onChange={handleAudioDeviceChange}>
                  {devices.audio.map((device, index) => (
                      <option key={device.deviceId} value={index}>
                        {device.label || device.deviceId || device.groupId}
                      </option>
                  ))}
                </select>
              </label>
            </>
          )}
        </div>
    );
};

// export default App;

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);

 

See also

  1. JavaScript - list available audio and video input devices (e.g. web cameras and microphones)

Referneces

  1. MediaDevices - MDN docs

  2. MediaDevices enumerateDevices() - MDN docs

Alternative titles

  1. React - list connected web cameras
  2. React - list connected microphones
  3. React - get available audio and video input devices list
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join