speech-input.tsx 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. * Derived from vercel/ai-elements (skills/ai-elements/scripts/speech-input.tsx).
  3. * Copyright 2023 Vercel, Inc. Licensed under Apache-2.0.
  4. * Modified by ZCode: local integration, formatting and adaptations.
  5. * See THIRD-PARTY-NOTICES.md in the repository root for license and provenance.
  6. */
  7. "use client";
  8. import { SpeechInput } from "@/components/ai-elements/speech-input";
  9. import { useCallback, useState } from "react";
  10. /**
  11. * Fallback handler for browsers that don't support Web Speech API (Firefox, Safari).
  12. * This function receives recorded audio and should send it to a transcription service.
  13. * Example uses OpenAI Whisper API - replace with your preferred service.
  14. */
  15. const handleAudioRecorded = async (audioBlob: Blob): Promise<string> => {
  16. const formData = new FormData();
  17. formData.append("file", audioBlob, "audio.webm");
  18. formData.append("model", "whisper-1");
  19. const response = await fetch("https://api.openai.com/v1/audio/transcriptions", {
  20. body: formData,
  21. headers: {
  22. Authorization: `Bearer ${process.env.NEXT_PUBLIC_OPENAI_API_KEY}`,
  23. },
  24. method: "POST",
  25. });
  26. if (!response.ok) {
  27. throw new Error("Transcription failed");
  28. }
  29. const data = await response.json();
  30. return data.text;
  31. };
  32. const Example = () => {
  33. const [transcript, setTranscript] = useState("");
  34. const handleTranscriptionChange = useCallback((text: string) => {
  35. setTranscript((prev) => {
  36. const newText = prev ? `${prev} ${text}` : text;
  37. return newText;
  38. });
  39. }, []);
  40. const handleClear = useCallback(() => {
  41. setTranscript("");
  42. }, []);
  43. return (
  44. <div className="flex size-full flex-col items-center justify-center gap-4">
  45. <div className="flex gap-2">
  46. <SpeechInput
  47. onAudioRecorded={handleAudioRecorded}
  48. onTranscriptionChange={handleTranscriptionChange}
  49. size="icon"
  50. variant="outline"
  51. />
  52. {transcript && (
  53. <button
  54. className="text-muted-foreground text-sm underline hover:text-foreground"
  55. onClick={handleClear}
  56. type="button"
  57. >
  58. Clear
  59. </button>
  60. )}
  61. </div>
  62. {transcript ? (
  63. <div className="max-w-md rounded-lg border bg-card p-4 text-sm">
  64. <p className="text-muted-foreground">
  65. <strong>Transcript:</strong>
  66. </p>
  67. <p className="mt-2">{transcript}</p>
  68. </div>
  69. ) : (
  70. <p className="text-muted-foreground text-sm">Click the microphone to start speaking</p>
  71. )}
  72. </div>
  73. );
  74. };
  75. export default Example;