import React, { useEffect, useRef, useState } from "react"
export const AudioProcessor = () => {
const [isRecording, setIsRecording] = useState(false)
const [error, setError] = useState(null)
const audioContextRef = useRef(null)
const mediaRecorderRef = useRef(null)
useEffect(() => {
if (!audioContextRef.current) {
audioContextRef.current = new (window.AudioContext ||
window.webkitAudioContext)()
}
}, [])
const handleStartRecording = async () => {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
const audioContext = audioContextRef.current
const source = audioContext.createMediaStreamSource(stream)
const processor = audioContext.createScriptProcessor(1024, 1, 1)
source.connect(processor)
processor.connect(audioContext.destination)
processor.onaudioprocess = (e) => {
const audioData = e.inputBuffer.getChannelData(0)
console.log("Audio data:", audioData)
}
mediaRecorderRef.current = new MediaRecorder(stream)
mediaRecorderRef.current.start()
mediaRecorderRef.current.ondataavailable = (e) => {
const audioBlob = new Blob([e.data], { type: "audio/wav" })
console.log("Audio Blob:", audioBlob)
}
setIsRecording(true)
} catch (err) {
console.error("Error accessing microphone:", err)
setError(
"Permission to access microphone was denied. Please allow access and try again."
)
}
}
const handleStopRecording = () => {
if (mediaRecorderRef.current) {
mediaRecorderRef.current.stop()
}
setIsRecording(false)
}
return (
<div>
<button
onClick={isRecording ? handleStopRecording : handleStartRecording}>
{isRecording ? "Stop Recording" : "Start Recording"}
</button>
{error && <p style={{ color: "red" }}>{error}</p>}
</div>
)
}