Issue capturing user audio on Safari / iPhone through react web app

42 Views Asked by At

I am unable to capture audio recording from my React web app front end.
While it works on Chrome browsers (Windows, Mac and Android phones), there seems to be some issue when trying to capture audio in the following scenario -

  1. Chrome browser ONLY ON iPhones

  2. Safari browser on Mac OS and iPhones

Sharing the functions that are capturing and transmitting the audio to the server.

const [mediaRecorder, setMediaRecorder] = useState(null);
const [hasStarted, setHasStarted] = useState(false);
const [chatStatus, setChatStatus] = useState(false);
const id = useRef(uuid());
const audioChunksRef = useRef([]);

const startRecording = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      const mediaRecorder = new MediaRecorder(stream);

      mediaRecorder.ondataavailable = (event) => {
        audioChunksRef.current.push(event.data);
      };

      mediaRecorder.start();
      setMediaRecorder(mediaRecorder);
      setIsRecording(true);
    } catch (error) {
      console.error('Error starting recording:', error);
    }
  };

  const stopRecording = async () => {
    if (mediaRecorder) {
      mediaRecorder.onstop = async () => {

        const audioBlob = new Blob(audioChunksRef.current, {
          type: 'audio/mp3',
        });
        const formData = new FormData();
        formData.append('audio', audioBlob, 'audio_recording.mp3');
        formData.append('id', id.current);

        const response = await fetch(`${URL}/upload-audio`, {
          method: 'POST',
          body: formData,
          credentials: 'include',
        }).catch((error) => {
          console.error('Fetch error:', error);
          throw error; // Re-throw the error to handle it in the onstop handler
        });
        const { lastMessage, chatStatus } = await response.json();
        console.log(lastMessage);
        setResponseText(lastMessage);
        setChatStatus(chatStatus);
        audioChunksRef.current = [];
        mediaRecorder.stream.getTracks().forEach((track) => track.stop());
        setMediaRecorder(null);
      };
      mediaRecorder.stop();
      setIsRecording(false);
    }
  };
0

There are 0 best solutions below