Last active
November 2, 2022 15:48
-
-
Save anotherlab/69efe891f0363deec390143247a7d92d to your computer and use it in GitHub Desktop.
PowerShell script to convert a WebVTT caption file (*.vtt) to SubRip (*.srt)
This file contains 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
# SRT File format https://docs.fileformat.com/video/srt/ | |
# WebVTT file format https://developer.mozilla.org/en-US/docs/Web/API/WebVTT_API | |
param ( | |
[Parameter(Mandatory = $true)][string]$localPath | |
) | |
# Get all of the matching file names | |
$MatchingFileNames = (Get-ChildItem $localPath -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 WebVTT file | |
$IsVTT = $file_data[0] -like 'WEBVTT*' | |
if ($IsVTT -eq $True) | |
{ | |
# Generate the destination filename | |
$srtFilename = [io.path]::ChangeExtension($MatchingFileName.FullName, 'srt') | |
$new_data = New-Object System.Collections.Generic.List[System.Object] | |
Write-Host ('Reading ' + $MatchingFileName.FullName ) | |
$CurentLine = 2 | |
$Counter = 1 | |
while ($CurentLine -lt $file_data.Length) | |
{ | |
$ThisLine = $file_data[$CurentLine] | |
$ThisTime = $ThisLine.Split(" ") | |
if ($ThisTime.Length -eq 3) | |
{ | |
if ($ThisTime[1] -eq "-->") | |
{ | |
$ThisLine = $ThisLine.Replace('.', ',') | |
$new_data.Add($Counter++) | |
$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] | |
while ($caption -ne '') | |
{ | |
$new_data.Add($caption) | |
$caption = $file_data[++$CurentLine] | |
} | |
$new_data.Add($caption) | |
} | |
} | |
$CurentLine++ | |
} | |
# Write out the converted data | |
Write-Host ('Writinging ' + $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