-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathsubtitle-parser.ts
62 lines (49 loc) · 1.59 KB
/
subtitle-parser.ts
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
import axios from 'axios'
import vttToJson from 'vtt-to-json'
const { default: srtParser2 } = require('srt-parser-2')
import { Subtitle } from '../'
import timeToSeconds from './time-to-seconds'
const subtitleParser = async (subitleUrl: string): Promise<Subtitle[]> => {
const { data: subtitleData } = await axios.get(subitleUrl)
const subtitleType = subitleUrl.split('.')[subitleUrl.split('.').length - 1]
const result: Subtitle[] = []
if (subtitleType === 'srt') {
interface srtParserSubtitle {
startTime: string
endTime: string
text: string
}
const parser: {
fromSrt: (data: any) => srtParserSubtitle[]
} = new srtParser2()
const parsedSubtitle: srtParserSubtitle[] = parser.fromSrt(subtitleData)
parsedSubtitle.forEach(({ startTime, endTime, text }) => {
result.push({
start: timeToSeconds(startTime.split(',')[0]),
end: timeToSeconds(endTime.split(',')[0]),
part: text,
})
})
}
if (subtitleType === 'vtt') {
interface vttToJsonSubtitle {
start: number
end: number
part: string
}
const parsedSubtitle: vttToJsonSubtitle[] = await vttToJson(subtitleData)
parsedSubtitle.forEach(({ start, end, part }) => {
// For some reason this library adds the index of the subtitle at the end of the part, so we cut it
result.push({
start: start / 1000,
end: end / 1000,
part: part.slice(
0,
part.length - part.split(' ')[part.split(' ').length - 1].length,
),
})
})
}
return result
}
export default subtitleParser