Teleprompter.js
3.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
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import React from 'react'
import styled from 'styled-components'
import stringSimilarity from 'string-similarity'
const StyledTeleprompter = styled.div`
font-size: 6rem;
width: 100%;
height: 35rem;
scroll-behavior: smooth;
overflow: auto;
display: block;
margin-bottom: 1rem;
`
// Userκ° μ§κΈ λ§νκ³ μλ λ¨μ΄ style
const Interim = styled.div`
background: rgb(0, 0, 0, 0.25);
color: white;
flex: 0 0 auto;
padding: 0.5rem;
border-radius: 1rem;
display: inline-block;
`
// Script λ¬Έμμ΄ μ²λ¦¬ ["I", "am", "happy"] -> "iamhappy"
const onlyWord = (word) =>
word
.trim() // λ¬Έμμ΄ μ’μ°μμ 곡백 μ κ±°
.toLocaleLowerCase() // μνλ²³ μλ¬Έμλ‘ λ³ν
.replace(/[^κ°-ν£γ±-γ
γ
-γ
£a-z]/gi, '') // μ κ·μμ μ΄μ©ν΄ νκΈ λλ μνλ²³μ΄ μλ λ¬Έμ λΉμΉΈμΌλ‘ λ³ν
export default function Teleprompter({ words, progress, listening, onChange }) {
const recog = React.useRef(null)
const scrollRef = React.useRef(null)
const [ results, setResults ] = React.useState('')
React.useEffect(() => {
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition
recog.current = new SpeechRecognition()
recog.current.continuous = true
recog.current.interimResults = true
}, [])
React.useEffect(() => {
if (listening) {
recog.current.start()
}
else {
recog.current.stop()
}
}, [listening])
React.useEffect(() => {
const handleResult = ({ results }) => {
const interim = Array.from(results)
.filter(r => !r.isFinal)
.map(r => r[0].transcript)
.join(' ')
setResults(interim)
const newIndex = interim
.split(' ')
.reduce((memo, word) => {
if ( memo >= words.length) {
return memo
}
const similarity = stringSimilarity.compareTwoStrings(
onlyWord(word),
onlyWord(words[memo])
)
memo +=
similarity > 0.3 // μ μ¬λ λ―Όκ°λ μ€μ
? 1
: 0
return memo
}, progress)
if ( newIndex > progress && newIndex <= words.length ) {
onChange(newIndex)
}
}
recog.current.addEventListener(
'result',
handleResult
)
return () => {
recog.current.removeEventListener(
'result',
handleResult
)
}
}, [onChange, progress, words])
React.useEffect(() => {
/* eslint-disable no-unused-expressions */
scrollRef.current
.querySelector(
`[data-index='${
progress + 8 // νμ¬ μ§ν μνμ λ°λΌ Scroll μ€μ
}']`
)
?.scrollIntoView({
behavior: 'smooth',
block: 'nearest',
inline: 'start'
})
}, [progress])
return (
<>
<StyledTeleprompter ref={scrollRef}>
{words.map((word, i) => (
<span
key={`${word}:${i}`}
data-index={i}
style={{
color:
i < progress
? '#000' // μμ§ μ½μ§ μμ wordλ ν°μ
: '#ccc' // μ½μ wordλ κ²μμμΌλ‘ λ³κ²½
}}
>
{word}{' '}
</span>
))}
</StyledTeleprompter>
{results && ( <Interim>{results}</Interim> )}
</>
)
}