Сдвинуть субтитры по времени
Добавляет или вычитает секунды из всех таймкодов SRT и сохраняет новый файл.
Что делает скрипт
Скрипт разбирает строки вида 00:01:02,500 --> 00:01:05,000, добавляет смещение и собирает файл заново. Отрицательные значения обрезаются до нуля, поэтому дорожка не ломается. Исходный SRT не изменяется, результат пишется рядом.
- После сдвига проверьте синхронизацию в плеере, особенно на длинных дорожках.
Быстрый старт
powershell -File Shift-Subtitles.ps1 -InputPath subtitles.srt -Seconds 1.5
Скачайте файл, откройте терминал в папке со скриптом и выполните команду. Запускайте в PowerShell 5.1 или PowerShell 7.
Другие варианты
powershell -File Shift-Subtitles.ps1 -InputPath subtitles.srt -Seconds 1.5powershell -File Shift-Subtitles.ps1 -InputPath movie.srt -Seconds -0.75 -OutputPath fixed.srtpowershell -File Shift-Subtitles.ps1 -InputPath subs.srt -Seconds 2
Что понадобится
Встроен в Windows 10/11 (PowerShell 5.1)
Shift-Subtitles.ps1
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$InputPath,
[Parameter(Mandatory = $true)]
[ValidateRange(-86400.0, 86400.0)]
[double]$Seconds,
[string]$OutputPath
)
$ErrorActionPreference = 'Stop'
if (-not (Test-Path -LiteralPath $InputPath -PathType Leaf)) {
throw "Файл субтитров не найден: $InputPath"
}
$source = (Resolve-Path -LiteralPath $InputPath).Path
if (-not $OutputPath) {
$directory = Split-Path -Parent $source
$name = [IO.Path]::GetFileNameWithoutExtension($source)
$OutputPath = Join-Path $directory "${name}_shifted.srt"
}
$target = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutputPath)
if ($target -eq $source) {
throw 'Результат не должен совпадать с исходным файлом.'
}
function Format-SrtTime {
param([int64]$Milliseconds)
if ($Milliseconds -lt 0) {
$Milliseconds = 0
}
$hours = [int64][math]::Floor($Milliseconds / 3600000)
$minutes = [int64][math]::Floor(($Milliseconds % 3600000) / 60000)
$secondsPart = [int64][math]::Floor(($Milliseconds % 60000) / 1000)
$millis = [int64]($Milliseconds % 1000)
return ('{0:00}:{1:00}:{2:00},{3:000}' -f $hours, $minutes, $secondsPart, $millis)
}
$pattern = '^(\d{2}):(\d{2}):(\d{2}),(\d{3}) --> (\d{2}):(\d{2}):(\d{2}),(\d{3})(.*)$'
$offsetMs = [int64][math]::Round($Seconds * 1000)
$lines = Get-Content -LiteralPath $source -Encoding UTF8
$output = New-Object System.Collections.Generic.List[string]
$shifted = 0
$clamped = 0
foreach ($line in $lines) {
if ($line -match $pattern) {
$startMs = (([int64]$matches[1] * 3600 + [int64]$matches[2] * 60 + [int64]$matches[3]) * 1000) + [int64]$matches[4]
$endMs = (([int64]$matches[5] * 3600 + [int64]$matches[6] * 60 + [int64]$matches[7]) * 1000) + [int64]$matches[8]
$newStart = $startMs + $offsetMs
$newEnd = $endMs + $offsetMs
if ($newStart -lt 0) {
$newStart = 0
$clamped++
}
if ($newEnd -lt 0) {
$newEnd = 0
$clamped++
}
$line = '{0} --> {1}{2}' -f (Format-SrtTime $newStart), (Format-SrtTime $newEnd), $matches[9]
$shifted++
}
$output.Add($line)
}
$directory = Split-Path -Parent $target
if (-not (Test-Path -LiteralPath $directory)) {
New-Item -ItemType Directory -Path $directory -Force | Out-Null
}
$encoding = [System.Text.UTF8Encoding]::new($false)
[System.IO.File]::WriteAllLines($target, $output, $encoding)
Write-Host "Сдвинуто строк: $shifted, обрезано по нулю: $clamped"
Write-Host "Готово: $target"
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.