|
1 package nl.inlet42.data.subtitles { |
|
2 |
|
3 /** |
|
4 * @author Jankees.van.Woezik |
|
5 */ |
|
6 public class SubtitleParser { |
|
7 public static function parseSRT(data : String) : Array { |
|
8 var result : Array = new Array(); |
|
9 |
|
10 var lines : Array; |
|
11 var translation : SubTitleData; |
|
12 |
|
13 var blocks : Array = data.split(/^[0-9]+$/gm); |
|
14 for each (var block : String in blocks) { |
|
15 translation = new SubTitleData(); |
|
16 lines = block.split(/[\r\n]+/); |
|
17 for each (var line : String in lines) { |
|
18 //all lines in a translation block |
|
19 if(trim(line) != "") { |
|
20 if(line.match("-->")) { |
|
21 //timecodes line |
|
22 var timecodes : Array = line.split(/[ ]+-->[ ]+/gm); |
|
23 if(timecodes.length != 2) { |
|
24 trace("Translation error, something wrong with the start or end time"); |
|
25 } else { |
|
26 translation.start = stringToSeconds(timecodes[0]); |
|
27 translation.end = stringToSeconds(timecodes[1]); |
|
28 translation.startStr = timecodes[0].replace(",","."); |
|
29 translation.endStr = timecodes[1].replace(",","."); |
|
30 translation.duration = translation.end - translation.start; |
|
31 if(translation.duration < 0) { |
|
32 trace("Translation error, something wrong with the start or end time"); |
|
33 } |
|
34 } |
|
35 } else { |
|
36 //translation line |
|
37 if(translation.text.length != 0) line = "\n" + trim(line); |
|
38 translation.text += line; |
|
39 } |
|
40 } |
|
41 } |
|
42 result.push(translation); |
|
43 } |
|
44 return result; |
|
45 } |
|
46 |
|
47 public static function trim(p_string : String) : String { |
|
48 if (p_string == null) { |
|
49 return ''; |
|
50 } |
|
51 return p_string.replace(/^\s+|\s+$/g, ''); |
|
52 } |
|
53 |
|
54 /** |
|
55 * Convert a string to seconds, with these formats supported: |
|
56 * 00:03:00.1 / 03:00.1 / 180.1s / 3.2m / 3.2h / 00:01:53,800 |
|
57 * |
|
58 * Special thanks to Thijs Broerse of Media Monks! |
|
59 * |
|
60 **/ |
|
61 public static function stringToSeconds(string : String) : Number { |
|
62 var arr : Array = string.split(':'); |
|
63 var sec : Number = 0; |
|
64 if (string.substr(-1) == 's') { |
|
65 sec = Number(string.substr(0, string.length - 1)); |
|
66 }else if (string.substr(-1) == 'm') { |
|
67 sec = Number(string.substr(0, string.length - 1)) * 60; |
|
68 }else if(string.substr(-1) == 'h') { |
|
69 sec = Number(string.substr(0, string.length - 1)) * 3600; |
|
70 }else if(arr.length > 1) { |
|
71 if(arr[2] && String(arr[2]).indexOf(',') != -1) arr[2] = String(arr[2]).replace(/\,/, "."); |
|
72 sec = Number(arr[arr.length - 1]); |
|
73 sec += Number(arr[arr.length - 2]) * 60; |
|
74 if(arr.length == 3) { |
|
75 sec += Number(arr[arr.length - 3]) * 3600; |
|
76 } |
|
77 } else { |
|
78 sec = Number(string); |
|
79 } |
|
80 return sec; |
|
81 } |
|
82 } |
|
83 } |