Fix SRT subtitle conversion and default selection

This commit is contained in:
Mert Uyanık
2025-10-29 14:22:08 +03:00
parent c5efcb95d5
commit a508919d20
2 changed files with 71 additions and 26 deletions
+49 -26
View File
@@ -2,34 +2,57 @@
* Parse SRT subtitle format to WebVTT
*/
export const parseSRT = (srtContent: string): string => {
const lines = srtContent.trim().split('\n')
let vttContent = 'WEBVTT\n\n'
const normalised = srtContent.replace(/\r\n/g, '\n').replace(/\r/g, '\n').trim()
let i = 0
while (i < lines.length) {
// Skip subtitle number
if (/^\d+$/.test(lines[i].trim())) {
i++
}
// Parse timestamp line
if (lines[i] && lines[i].includes('-->')) {
const timeLine = lines[i].replace(/,/g, '.') // SRT uses comma, VTT uses dot
vttContent += timeLine + '\n'
i++
// Add subtitle text
while (i < lines.length && lines[i].trim() !== '') {
vttContent += lines[i] + '\n'
i++
}
vttContent += '\n'
}
i++
if (!normalised) {
return 'WEBVTT\n\n'
}
return vttContent
const cues = normalised
.split(/\n{2,}/)
.map((cueBlock) => {
const lines = cueBlock
.split('\n')
.map((line) => line.replace(/^\ufeff/, '').trimEnd())
.filter((line, index, arr) => !(line === '' && index === arr.length - 1))
if (lines.length === 0) {
return null
}
if (/^\d+$/.test(lines[0].trim())) {
lines.shift()
}
if (lines.length === 0) {
return null
}
const timeLine = lines.shift()
if (!timeLine || !timeLine.includes('-->')) {
return null
}
const vttTimeLine = timeLine
.split('-->')
.map((part) => part.trim().replace(/,/g, '.'))
.join(' --> ')
if (!vttTimeLine.includes('-->')) {
return null
}
const text = lines.join('\n')
return `${vttTimeLine}\n${text}`.trim()
})
.filter((cueBlock): cueBlock is string => Boolean(cueBlock))
const header = 'WEBVTT\n\n'
if (cues.length === 0) {
return header
}
return header + cues.join('\n\n') + '\n'
}
/**
@@ -37,7 +60,7 @@ export const parseSRT = (srtContent: string): string => {
*/
export const createSubtitleBlobURL = (content: string, format: 'vtt' | 'srt'): string => {
const vttContent = format === 'srt' ? parseSRT(content) : content
const blob = new Blob([vttContent], { type: 'text/vtt' })
const blob = new Blob([vttContent], { type: 'text/vtt;charset=utf-8' })
return URL.createObjectURL(blob)
}