chengsokdara / use-whisper

React hook for OpenAI Whisper with speech recorder, real-time transcription, and silence removal built-in
MIT License
732 stars 137 forks source link

Cannot read properties of undefined (reading 'transcript') #44

Open salmancz opened 1 year ago

salmancz commented 1 year ago

Help me resolving this issue please. I tried to save 10seconds of transcript for 5times in an array and display it.

import React, { useState } from 'react';
import { useWhisper } from '@chengsokdara/use-whisper';
import './App.css';

const App = () => {
  const [transcriptions, setTranscriptions] = useState([]);
  const { startRecording, stopRecording } = useWhisper({
    apiKey: 'API_KEY', // Replace with your actual OpenAI API token
    streaming: true,
    removeSilence: true,
    timeSlice: 1000, // 1 second
    whisperConfig: {
      language: 'en',
    },
    onTranscribe: (blob) => {
      return new Promise((resolve) => {
        const reader = new FileReader();
        reader.onloadend = () => {
          const text = reader.result;
          resolve({ text });
        };
        reader.readAsText(blob);
      });
    },
  });

  const recordAndSave = async () => {
    const recordingResult = await startRecording();
    setTimeout(async () => {
      const transcription = await stopRecording();
      setTranscriptions((prevTranscriptions) => [...prevTranscriptions, recordingResult.transcript.text]);
    }, 10000); // Record for 10 seconds
  };

  const repeatRecording = async () => {
    for (let i = 0; i < 5; i++) {
      await recordAndSave();
    }
  };

  return (
    <div className="App">
      <header className="App-header">
        <h1>Real-Time Audio Transcription</h1>
      </header>
      <main>
        <div>
          <p>Transcribed Texts:</p>
          <ul>
            {transcriptions.map((text, index) => (
              <li key={index}>{text}</li>
            ))}
          </ul>
        </div>
        <div>
          <button onClick={repeatRecording}>Start Recording 5 Times</button>
        </div>
      </main>
    </div>
  );
};

export default App;

Screenshot from 2023-08-15 14-21-52