| import { useState, useRef } from "react"; | |
| import { Mic, Square, Loader2 } from "lucide-react"; | |
| import { GlassCard } from "@/components/ui/GlassCard"; | |
| interface VoiceMessageRecorderProps { | |
| onSend: (blob: Blob, duration: number) => Promise<void>; | |
| onCancel: () => void; | |
| } | |
| export function VoiceMessageRecorder({ onSend, onCancel }: VoiceMessageRecorderProps) { | |
| const [recording, setRecording] = useState(false); | |
| const [uploading, setUploading] = useState(false); | |
| const [duration, setDuration] = useState(0); | |
| const mediaRecorderRef = useRef<MediaRecorder | null>(null); | |
| const chunksRef = useRef<Blob[]>([]); | |
| const timerRef = useRef<NodeJS.Timeout | null>(null); | |
| const startRecording = async () => { | |
| const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); | |
| const mediaRecorder = new MediaRecorder(stream); | |
| mediaRecorderRef.current = mediaRecorder; | |
| chunksRef.current = []; | |
| mediaRecorder.ondataavailable = (e) => chunksRef.current.push(e.data); | |
| mediaRecorder.onstop = async () => { | |
| const blob = new Blob(chunksRef.current, { type: "audio/webm" }); | |
| setUploading(true); | |
| await onSend(blob, duration); | |
| setUploading(false); | |
| onCancel(); | |
| }; | |
| mediaRecorder.start(); | |
| setRecording(true); | |
| setDuration(0); | |
| timerRef.current = setInterval(() => setDuration((d) => d + 1), 1000); | |
| }; | |
| const stopRecording = () => { | |
| if (mediaRecorderRef.current && recording) { | |
| mediaRecorderRef.current.stop(); | |
| mediaRecorderRef.current.stream.getTracks().forEach((track) => track.stop()); | |
| setRecording(false); | |
| if (timerRef.current) clearInterval(timerRef.current); | |
| } | |
| }; | |
| return ( | |
| <GlassCard className="p-3 flex items-center gap-3"> | |
| {recording ? ( | |
| <> | |
| <div className="flex items-center gap-2"> | |
| <div className="w-3 h-3 bg-red-500 rounded-full animate-pulse" /> | |
| <span className="text-sm">{duration}s</span> | |
| </div> | |
| <button onClick={stopRecording} className="p-2 rounded-full bg-red-500 text-white"><Square className="w-4 h-4" /></button> | |
| </> | |
| ) : uploading ? ( | |
| <Loader2 className="animate-spin w-5 h-5" /> | |
| ) : ( | |
| <button onClick={startRecording} className="p-2 rounded-full bg-primary text-white"><Mic className="w-5 h-5" /></button> | |
| )} | |
| <button onClick={onCancel} className="text-gray-400 hover:text-gray-600">Cancel</button> | |
| </GlassCard> | |
| ); | |
| } |
Xet Storage Details
- Size:
- 2.47 kB
- Xet hash:
- c51987cd7b1ca986647f6967bbe59f0f554cf2eb01af4daa2cfc90df0de8d06a
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.