Meisam Nazari
Meisam Nazari

Reputation: 994

Camera is not working in android ionic react app

I have this code it is working in PC browser but in android it will not open the camera. The code is written in ionic framework using React components. The main component which opens camera is as below:

import React, { useRef, useState,useEffect } from 'react';
import './index.scss';

const CAPTURE_OPTIONS = {
  audio: true,
  video: { facingMode: "user" }
};

const Camera: React.FC = () => {
  const videoRef = useRef<any>(null);

  const [mediaStream, setMediaStream] = useState<any>(null);

  useEffect(() => {
    async function enableStream() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia(CAPTURE_OPTIONS);
        setMediaStream(stream);
      } catch (err) {
        // Removed for brevity
      }
    }

    if (!mediaStream) {
      enableStream();
    } else {
      return function cleanup() {
        mediaStream.getTracks().forEach((track: any) => {
          track.stop();
        });
      }
    }
  }, [mediaStream, CAPTURE_OPTIONS]);

  if (mediaStream && videoRef.current && !videoRef.current.srcObject) {
    videoRef.current.srcObject = mediaStream;
  }

  const handleCanPlay = () => {
    videoRef.current.play();
  }

  return (
    <div>
      <video ref={videoRef} onCanPlay={handleCanPlay} autoPlay playsInline loop muted className={"camera"} />
    </div>
  );
}

export default Camera;

Does anyone knows that what is the problem I have this problem for running the code on android capacitor and when I run ionic capacitor run android --livereload --external I cant get sth like below:

enter image description here

Upvotes: 2

Views: 1097

Answers (1)

NotJohn
NotJohn

Reputation: 98

When using webrtc and navigator.mediaDevices.getUserMedia() you need to make sure that you are using the adapter.js file.

You can use https://www.npmjs.com/package/webrtc-adapter, or copy the file from - https://github.com/webrtc/adapter/tree/master/release. If you want it globally put it in your public folder of your ionic project.

Upvotes: 1

Related Questions