Spaces:
Sleeping
Sleeping
| import { useState, useCallback } from 'react'; | |
| export const useAudioRecorder = () => { | |
| const [isRecording, setIsRecording] = useState(false); | |
| const [audioURL, setAudioURL] = useState<string | null>(null); | |
| const [mediaRecorder, setMediaRecorder] = useState<MediaRecorder | null>(null); | |
| const [audioChunks, setAudioChunks] = useState<Blob[]>([]); | |
| const startRecording = useCallback(async () => { | |
| try { | |
| const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); | |
| const recorder = new MediaRecorder(stream); | |
| recorder.ondataavailable = (event) => { | |
| setAudioChunks(current => [...current, event.data]); | |
| }; | |
| recorder.onstop = () => { | |
| const audioBlob = new Blob(audioChunks, { type: 'audio/wav' }); | |
| const audioUrl = URL.createObjectURL(audioBlob); | |
| setAudioURL(audioUrl); | |
| }; | |
| recorder.start(); | |
| setMediaRecorder(recorder); | |
| setIsRecording(true); | |
| } catch (error) { | |
| console.error('Erreur lors de l\'accès au microphone:', error); | |
| } | |
| }, [audioChunks]); | |
| const stopRecording = useCallback(() => { | |
| if (mediaRecorder && isRecording) { | |
| mediaRecorder.stop(); | |
| setIsRecording(false); | |
| mediaRecorder.stream.getTracks().forEach(track => track.stop()); | |
| } | |
| }, [mediaRecorder, isRecording]); | |
| const playRecording = useCallback(() => { | |
| if (audioURL) { | |
| const audio = new Audio(audioURL); | |
| audio.play(); | |
| } | |
| }, [audioURL]); | |
| return { | |
| isRecording, | |
| audioURL, | |
| startRecording, | |
| stopRecording, | |
| playRecording | |
| }; | |
| }; |