Created
April 5, 2025 16:31
-
-
Save anotherlab/7f3a82639ead91a55cfbd19ec474f3f1 to your computer and use it in GitHub Desktop.
PowerShell script to convert SRT files to VTT
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
# Reads SRT and writes VTT | |
param ( | |
[Parameter(Mandatory = $true)][string]$SrcPath | |
) | |
# Get all of the matching file names | |
$MatchingFileNames = (Get-ChildItem $SrcPath -File) | sort-Object Name | |
# walk through the list of files | |
foreach($MatchingFileName in $MatchingFileNames) { | |
$file_data = Get-Content $MatchingFileName | |
# Verify that we are reading a SRT file | |
$IsSRT = $file_data[0] -like '1' | |
if ($IsSRT -eq $True) { | |
# Another check to see if we are reading a SRT file | |
$ThisTime = $file_data[1].Split(" ") | |
if ($ThisTime.Length -eq 3) { | |
$IsSRT = $ThisTime[1] -eq "-->" | |
} else { | |
$IsSRT = $false | |
} | |
} | |
if ($IsSRT -eq $True) { | |
# Generate the destination filename | |
$srtFilename = [io.path]::ChangeExtension($MatchingFileName.FullName, 'vtt') | |
$new_data = New-Object System.Collections.Generic.List[System.Object] | |
$new_data.Add("WEBVTT") | |
$new_data.Add("") | |
Write-Host ('Reading ' + $MatchingFileName.FullName ) | |
$CurentLine = 1 | |
while ($CurentLine -lt $file_data.Length) { | |
$percent = ($CurentLine * 100 / $file_data.Length) | |
Write-Progress -Activity "Processing $MatchingFileName.FullName to $srtFilename" -Status "$percent% complete" -PercentComplete $percent | |
$ThisLine = $file_data[$CurentLine] | |
$ThisTime = $ThisLine.Split(" ") | |
if ($ThisTime.Length -eq 3) { | |
if ($ThisTime[1] -eq "-->") { | |
# Change the time format from SRT to VTT | |
$ThisLine = $ThisLine.Replace(',', '.') | |
$new_data.Add($ThisLine) | |
$CurentLine++ | |
# Read the next set of lines for the caption | |
# Treat as caption until the next blank line | |
$caption = $file_data[$CurentLine] | |
# $currentCaption = '' | |
while ($caption -ne '' -and $CurentLine -lt $file_data.Length) { | |
$new_data.Add($caption) | |
$caption = $file_data[++$CurentLine] | |
} | |
$new_data.Add($caption) | |
} | |
} | |
$CurentLine++ | |
} | |
# Write out the converted data | |
Write-Host ('Writing ' + $srtFilename ) | |
Out-File -FilePath $srtFilename -InputObject $new_data | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment