giovani-rubim

Sync Subtitles Node.js

Jan 10th, 2021
894
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const fs = require('fs')
  2. const path_in = './<original>.srt'
  3. const path_out = './<output>.srt'
  4. const input_encoding = 'latin1'
  5. const output_encoding = 'latin1'
  6.  
  7. const src = fs.readFileSync(path_in).toString(input_encoding)
  8.  
  9. const parseTime = (time) => {
  10.     const [h, m, s] = time
  11.         .replace(',', '.')
  12.         .split(':')
  13.         .map(Number)
  14.     return (h*60 + m)*60 + s
  15. }
  16.  
  17. const toTime = (parsed) => {
  18.     const s = parsed % 60
  19.     parsed = Math.round((parsed - s)/60)
  20.     const m = parsed % 60
  21.     const h = Math.round((parsed - m)/60)
  22.     return `${
  23.         h.toString().padStart(2,0)
  24.     }:${
  25.         m.toString().padStart(2,0)
  26.     }:${
  27.         s.toFixed(3).padStart(6,0).replace('.', ',')
  28.     }`
  29. }
  30.  
  31. // Calculate speed change and displacement
  32. // const cur_t0 = parseTime('00:02:03,924')
  33. // const cur_t1 = parseTime('00:44:42,015')
  34. // const fix_t0 = parseTime('00:02:03,924')
  35. // const fix_t1 = parseTime('00:44:42,015')
  36. // const mul = (fix_t1 - fix_t0)/(cur_t1 - cur_t0)
  37. // const sum = fix_t0 - cur_t0*mul
  38.  
  39. // Define displacement with no speed change
  40. const mul = 1
  41. const sum = 6.5
  42.  
  43. const res = src
  44.     .replace(/\r/g, '')
  45.     .trim()
  46.     .split(/\n\n/)
  47.     .map(sub => {
  48.         let [, n, a, b, text ] = sub
  49.             .trim()
  50.             .match(/^(\d+)\s+([^\s]+) --> ([^\s]+)\s+((.|\s)*)$/)
  51.         a = toTime(parseTime(a)*mul + sum)
  52.         b = toTime(parseTime(b)*mul + sum)
  53.         return `${n}\n${a} --> ${b}\n${text}\n\n`
  54.     })
  55.     .join('')
  56.     .replace(/\n/g, '\r\n')
  57.  
  58. fs.writeFileSync(path_out, Buffer.from(res, output_encoding))
  59.  
RAW Paste Data