File size: 4,450 Bytes
4a135f5
 
 
 
 
 
 
 
 
 
 
 
 
b092906
 
4a135f5
 
 
 
 
 
 
 
 
b092906
4a135f5
 
 
78556ed
 
4a135f5
 
78556ed
4a135f5
78556ed
4a135f5
78556ed
 
4a135f5
 
 
 
 
 
 
b092906
 
 
4a135f5
b092906
 
 
4a135f5
b092906
4a135f5
b092906
 
78556ed
b092906
 
 
 
 
4a135f5
b092906
 
 
 
 
 
 
78556ed
b092906
 
 
 
4a135f5
b092906
 
 
 
4a135f5
 
b092906
 
 
4a135f5
 
 
b092906
 
 
 
 
 
 
 
 
 
 
 
 
ecf5c25
 
 
 
 
 
 
b092906
78556ed
 
4a135f5
ecf5c25
4a135f5
 
 
 
 
 
78556ed
 
 
 
 
 
 
 
51803b9
78556ed
 
 
 
 
 
 
ecf5c25
 
 
 
 
 
 
 
 
78556ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
import React, { useRef, useState } from "react";
import Loader from "./Loader";

const SILENCE_THRESHOLD = 0.01;
const SILENCE_DURATION = 1500;

export default function VoiceBot() {
  const mediaRecorderRef = useRef(null);
  const audioChunksRef = useRef([]);
  const analyserRef = useRef(null);
  const audioContextRef = useRef(null);
  const silenceTimerRef = useRef(null);
  const streamRef = useRef(null);
  const listeningRef = useRef(false);


  const [status, setStatus] = useState("idle");
  // idle | listening | thinking | speaking

  // =========================
  // START RECORDING
  // =========================
  const startRecording = async () => {
    setStatus("listening");
    listeningRef.current = true;
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    streamRef.current = stream;

    const recorder = new MediaRecorder(stream);
    mediaRecorderRef.current = recorder;
    audioChunksRef.current = [];

    recorder.ondataavailable = (e) => {
      audioChunksRef.current.push(e.data);
    };

    recorder.onstop = handleStop;
    recorder.start();

    setupSilenceDetection(stream);
  };

  // =========================
  // SILENCE DETECTION
  // =========================
 const setupSilenceDetection = (stream) => {
  audioContextRef.current = new AudioContext();
  const source = audioContextRef.current.createMediaStreamSource(stream);

  analyserRef.current = audioContextRef.current.createAnalyser();
  analyserRef.current.fftSize = 2048;
  source.connect(analyserRef.current);

  const data = new Uint8Array(analyserRef.current.fftSize);

  const checkSilence = () => {
    analyserRef.current.getByteTimeDomainData(data);

    let sum = 0;
    for (let i = 0; i < data.length; i++) {
      const v = (data[i] - 128) / 128;
      sum += v * v;
    }

    const volume = Math.sqrt(sum / data.length);

    if (volume < SILENCE_THRESHOLD) {
      if (!silenceTimerRef.current) {
        silenceTimerRef.current = setTimeout(() => {
          stopRecording();
        }, SILENCE_DURATION);
      }
    } else {
      clearTimeout(silenceTimerRef.current);
      silenceTimerRef.current = null;
    }

    // ✅ FIX: use ref, not React state
    if (listeningRef.current) {
      requestAnimationFrame(checkSilence);
    }
  };

  checkSilence();
};

  // =========================
  // STOP RECORDING
  // =========================
const stopRecording = () => {
  listeningRef.current = false;

  if (silenceTimerRef.current) {
    clearTimeout(silenceTimerRef.current);
    silenceTimerRef.current = null;
  }

  if (mediaRecorderRef.current?.state !== "inactive") {
    mediaRecorderRef.current.stop();
  }

  streamRef.current?.getTracks().forEach(t => t.stop());

  if (
    audioContextRef.current &&
    audioContextRef.current.state !== "closed"
  ) {
    audioContextRef.current.close();
  }
};




  // =========================
  // SEND TO BACKEND
  // =========================
  const handleStop = async () => {
    setStatus("thinking");

    const blob = new Blob(audioChunksRef.current, {
      type: "audio/wav",
    });

    const formData = new FormData();
    formData.append("audio", blob);

    const response = await fetch(
      "https://durga-7780-voicebot.hf.space/api/process-audio",
      {
        method: "POST",
        body: formData,
      }
    );

    const data = await response.json();

if (!response.ok || !data.audio_url) {
  console.error("Backend error:", data);
  setStatus("idle"); 
  return;
}

playBotAudio(data.audio_url);

  };

  // =========================
  // PLAY BOT AUDIO
  // =========================
  const playBotAudio = (url) => {
    setStatus("speaking");

    const audio = new Audio(url + "?t=" + Date.now());
    audio.onended = () => setStatus("idle");
    audio.play();
  };

  // =========================
  // UI
  // =========================
  return (
    <div style={styles.container}>
      {status === "idle" ? (
        <button onClick={startRecording} style={styles.mic}>
          🎤
        </button>
      ) : (
        <Loader />
      )}
    </div>
  );
}

const styles = {
  container: {
    height: "100vh",
    background: "#111",
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
  },
  mic: {
    width: 120,
    height: 120,
    borderRadius: "50%",
    fontSize: 40,
    background: "#4CAF50",
    color: "#fff",
    border: "none",
    cursor: "pointer",
  },
};