I'm trying to make my own video parody with custom subtitles. Creating your own custom subtitles file in a text editor with the SubRip or .SRT format is easy to do, it looks like this:

enter image description here

Where 00:00:20,000 is in hours:minutes:seconds,milliseconds format.

My question is really more about the manipulation needed to hack my text into .srt in a more elegant way...

Here's the text (scraped from a website) to parse:

downfall = Import["http://pastebin.com/raw/d6nmE5sT", "Text"]

enter image description here

And my code that parses it:

ss2=MapColumn[1,StringCases[#,t1___~~" - "~~t2___:>{t1,t2}][[1]]&,ss1];
ss4=MapAt[StringRiffle[##," --> "]&,ss3,{All,1}]

So far it works, but is brittle, and there are a few specify problems I'd like to fix:

  1. I can't directly export the ".srt" because it's not a 'known' format to mathematica, hence the rename hack.
  2. My string parsing is a bit overcomplicated.
  3. Instead of opening another video editing app like VLC and then importing, I'd like to write the captions into the video file though mathematica (into the frames).



Here is an example of formating the srt file. Since it is a text file, it can be exported using the "String" option:

exportRST[path_, string_] := Module[{formateLine, strLs,},
  formateLine[str_] := Module[{timePos, times, text},
    timePos = StringPosition[str, _ ~~ ":" ~~ _ ~~ _ ~~ "." ~~ _ ~~ _];
    times = StringTake[str, #] & /@ timePos;
    text = StringTake[str, {Last[Flatten@timePos] + 1, -1}];
    StringRiffle["00:" <> StringTake[#, {1, 4}] <> "," <> StringTake[str, {6, 7}] <> "0" & /@ times, " --> "] <> "\n" <>text
  strLs = formateLine /@ StringSplit[string, "\n"]; 
  Export[path, StringRiffle[StringRiffle[#, "\n"] & /@ Transpose[{ToString /@ Range[Length@strLs], strLs}], "\n\n"], "String"]

exportRST["~/Downloads/python.rst", downfall]

In order to encode the caption using Mathematica, it would require processing each frame in the video, which can take a very long time (It takes me forever to import the video you linked). It would be much convenient and efficient to use VLC or ffmpeg to encode the subtitles. For instance, here and here are detailed steps of how to do that in VLC and ffmpeg.

If you don't want to leave Mathematica, ffmpeg can be run as an external program using Get

<<"! ffmpeg -i input.avi -sub_charenc ISO-8859-1 -i subtitle.srt -vcodec h264 -acodec ac3 -scodec srt -metadata:s:s:0 language=ita output2.mkv"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.