Skip to content

Commit 1da9caa

Browse files
committed
Allow shorter recordings
1 parent d716cc2 commit 1da9caa

File tree

1 file changed

+49
-24
lines changed

1 file changed

+49
-24
lines changed

Diff for: src/RecordAudio.tsx

+49-24
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,64 @@
1-
import { FC, useState } from "react";
1+
import { FC, useState, useEffect } from "react";
22

33
const RecordAudio: FC<{ onCreated: (blob: Blob) => void }> = ({
44
onCreated,
55
}) => {
66
const [isRecording, setIsRecording] = useState(false);
77

8-
const startRecording = async () => {
9-
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
8+
// stop after 10s
9+
useEffect(() => {
10+
if (!isRecording) return;
1011

11-
const recorder = new MediaRecorder(stream);
12-
const chunks: Blob[] = [];
13-
recorder.ondataavailable = (event) => {
14-
chunks.push(event.data);
15-
};
16-
recorder.onstop = () => {
17-
const audioBlob = new Blob(chunks, { type: recorder.mimeType });
18-
onCreated(audioBlob);
19-
};
12+
const timer = setTimeout(() => setIsRecording(false), 10000);
13+
14+
return () => clearTimeout(timer);
15+
}, [isRecording]);
16+
17+
//
18+
useEffect(() => {
19+
if (!isRecording) return;
20+
21+
const stream = navigator.mediaDevices.getUserMedia({ audio: true });
22+
23+
const recorder = stream.then((stream) => {
24+
const recorder = new MediaRecorder(stream);
25+
const chunks: Blob[] = [];
26+
recorder.ondataavailable = (event) => {
27+
chunks.push(event.data);
28+
};
29+
recorder.onstop = () => {
30+
const audioBlob = new Blob(chunks, { type: recorder.mimeType });
2031

21-
recorder.start();
22-
setIsRecording(true);
23-
setTimeout(() => {
24-
recorder?.stop();
25-
setIsRecording(false);
32+
if (audioBlob.size < 1500) {
33+
console.warn("Skipping small blob", audioBlob);
34+
return;
35+
}
36+
37+
onCreated(audioBlob);
38+
};
39+
40+
recorder.start();
41+
42+
return recorder;
43+
});
44+
45+
return () => {
46+
recorder.then((recorder) => recorder.stop());
47+
stream.then((stream) =>
48+
stream.getTracks().forEach((track) => track.stop())
49+
);
50+
};
2651

27-
for (const track of stream.getTracks()) {
28-
track.stop();
29-
}
30-
}, 5000); // Stop recording after 5 seconds
31-
};
52+
// eslint-disable-next-line react-hooks/exhaustive-deps
53+
}, [isRecording]);
3254

3355
return (
3456
<div>
35-
<button onClick={startRecording} disabled={isRecording}>
36-
{isRecording ? "Recording..." : "Add Recording"}
57+
<button
58+
onClick={() => setIsRecording((prev) => !prev)}
59+
style={{ background: isRecording ? "red" : "" }}
60+
>
61+
{isRecording ? "Stop Recording" : "Start Recording"}
3762
</button>
3863
</div>
3964
);

0 commit comments

Comments
 (0)