-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathuseTrackTranscription.ts
More file actions
75 lines (70 loc) · 2.35 KB
/
useTrackTranscription.ts
File metadata and controls
75 lines (70 loc) · 2.35 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
import {
type ReceivedTranscriptionSegment,
addMediaTimestampToTranscription as addTimestampsToTranscription,
dedupeSegments,
// getActiveTranscriptionSegments,
getTrackReferenceId,
trackTranscriptionObserver,
type TrackReferenceOrPlaceholder,
// didActiveSegmentsChange,
} from '@livekit/components-core';
import type { TranscriptionSegment } from 'livekit-client';
import * as React from 'react';
import { useTrackSyncTime } from './useTrackSyncTime';
/**
* @alpha
* @deprecated Use useTranscription instead
*/
export interface TrackTranscriptionOptions {
/**
* how many transcription segments should be buffered in state
* @defaultValue 100
*/
bufferSize?: number;
/**
* optional callback for retrieving newly incoming transcriptions only
*/
onTranscription?: (newSegments: TranscriptionSegment[]) => void;
/** amount of time (in ms) that the segment is considered `active` past its original segment duration, defaults to 2_000 */
// maxAge?: number;
}
const TRACK_TRANSCRIPTION_DEFAULTS = {
bufferSize: 100,
// maxAge: 2_000,
} as const satisfies TrackTranscriptionOptions;
/**
* @returns An object consisting of `segments` with maximum length of opts.bufferSize
* @alpha
* @deprecated Use useTranscription instead
*/
export function useTrackTranscription(
trackRef: TrackReferenceOrPlaceholder | undefined,
options?: TrackTranscriptionOptions,
) {
const opts = { ...TRACK_TRANSCRIPTION_DEFAULTS, ...options };
const [segments, setSegments] = React.useState<Array<ReceivedTranscriptionSegment>>([]);
const syncTimestamps = useTrackSyncTime(trackRef);
const handleSegmentMessage = (newSegments: TranscriptionSegment[]) => {
opts.onTranscription?.(newSegments);
setSegments((prevSegments) =>
dedupeSegments(
prevSegments,
// when first receiving a segment, add the current media timestamp to it
newSegments.map((s) => addTimestampsToTranscription(s, syncTimestamps)),
opts.bufferSize,
),
);
};
React.useEffect(() => {
if (!trackRef?.publication) {
return;
}
const subscription = trackTranscriptionObserver(trackRef.publication).subscribe((evt) => {
handleSegmentMessage(...evt);
});
return () => {
subscription.unsubscribe();
};
}, [trackRef && getTrackReferenceId(trackRef), handleSegmentMessage]);
return { segments };
}