-
-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathRecord.tsx
More file actions
101 lines (82 loc) · 2.34 KB
/
Record.tsx
File metadata and controls
101 lines (82 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import React, { useRef, FC, useEffect } from 'react';
import {
AudioBuffer,
AudioContext,
AudioManager,
AudioRecorder,
AudioBufferSourceNode,
} from 'react-native-audio-api';
import { Container, Button } from '../../components';
const Record: FC = () => {
const recorderRef = useRef<AudioRecorder | null>(null);
const audioBuffersRef = useRef<AudioBuffer[]>([]);
const sourcesRef = useRef<AudioBufferSourceNode[]>([]);
const aCtxRef = useRef<AudioContext | null>(null);
useEffect(() => {
AudioManager.setAudioSessionOptions({
iosCategory: 'playAndRecord',
iosMode: 'spokenAudio',
iosOptions: ['allowBluetoothHFP', 'defaultToSpeaker'],
});
recorderRef.current = new AudioRecorder({
sampleRate: 16000,
bufferLengthInSamples: 16000,
});
}, []);
const onReplay = () => {
const aCtx = new AudioContext({ sampleRate: 16000 });
aCtxRef.current = aCtx;
if (aCtx.state === 'suspended') {
aCtx.resume();
}
const tNow = aCtx.currentTime;
let nextStartAt = tNow + 1;
const buffers = audioBuffersRef.current;
console.log(tNow, nextStartAt, buffers.length);
for (let i = 0; i < buffers.length; i++) {
const source = aCtx.createBufferSource();
source.buffer = buffers[i];
source.connect(aCtx.destination);
source.onended = () => {
console.log('Audio buffer source ended');
};
sourcesRef.current.push(source);
source.start(nextStartAt);
nextStartAt += buffers[i].duration;
}
setTimeout(
() => {
console.log('clearing data');
audioBuffersRef.current = [];
sourcesRef.current = [];
},
(nextStartAt - tNow) * 1000
);
};
const onRecord = () => {
if (!recorderRef.current) {
return;
}
recorderRef.current.onAudioReady((event) => {
const { buffer, numFrames, when } = event;
console.log(
'Audio recorder buffer ready:',
buffer.duration,
numFrames,
when
);
audioBuffersRef.current.push(buffer);
});
recorderRef.current.start();
setTimeout(() => {
recorderRef.current?.stop();
}, 3000);
};
return (
<Container centered>
<Button title="Record" onPress={onRecord} />
<Button title="Replay" onPress={onReplay} />
</Container>
);
};
export default Record;