Created
March 22, 2025 21:41
-
-
Save makiftutuncu/9fc13c707cde17c1dea1ae81a7087751 to your computer and use it in GitHub Desktop.
Shift timestamps in SRT formatted subtitle files in a folder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.BufferedWriter; | |
import java.io.IOException; | |
import java.nio.charset.StandardCharsets; | |
import java.nio.file.Files; | |
import java.nio.file.Path; | |
import java.nio.file.StandardOpenOption; | |
import java.time.LocalTime; | |
import java.time.format.DateTimeFormatter; | |
import java.time.temporal.ChronoUnit; | |
import java.util.Arrays; | |
import java.util.stream.Collectors; | |
public class SrtShifter { | |
private static final String timestampsPattern = "^\\d+:\\d{2}:\\d{2},\\d{3} --> \\d+:\\d{2}:\\d{2},\\d{3}$"; | |
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss,SSS"); | |
public static void main(String[] args) throws IOException { | |
if (args.length < 2) { | |
System.out.println("Pass folder path and shift duration in milliseconds as arguments!"); | |
return; | |
} | |
System.out.println(Arrays.toString(args)); | |
String path = args[0]; | |
int shiftInMs = Integer.parseInt(args[1]); | |
Files | |
.list(Path.of(path)) | |
.peek(System.out::println) | |
.filter(p -> p.toString().endsWith(".srt")) | |
.forEach(srt -> { | |
try { | |
process(srt, shiftInMs); | |
} catch (IOException e) { | |
throw new RuntimeException(e); | |
} | |
}); | |
} | |
private static void process(Path srt, int shiftInMs) throws IOException { | |
System.out.println("Processing " + srt.toAbsolutePath()); | |
BufferedWriter writer = Files.newBufferedWriter( | |
Path.of(srt.getParent().toString(), "_" + srt.getFileName()), StandardOpenOption.WRITE, StandardOpenOption.CREATE | |
); | |
Files | |
.readAllLines(srt, StandardCharsets.ISO_8859_1) | |
.stream() | |
.map(line -> { | |
if (!line.matches(timestampsPattern)) { | |
return line; | |
} | |
return Arrays | |
.stream(line.split(" --> ")) | |
.map(s -> LocalTime.parse(s, formatter).plus(shiftInMs, ChronoUnit.MILLIS)) | |
.map(lt -> lt.format(formatter)) | |
.collect(Collectors.joining(" --> ")); | |
}) | |
.forEach(line -> { | |
try { | |
writer.write(line); | |
writer.newLine(); | |
} catch (IOException e) { | |
throw new RuntimeException(e); | |
} | |
}); | |
writer.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment