// Polyfill for String.trim() in ExtendScript
if (typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
}
// ExtendScript for After Effects
// Begin undo group for script actions
app.beginUndoGroup("Create SubRip Comps with Modifications");
// Prompt user to select a SubRip (.srt) file
var srtFile = File.openDialog("Select a SubRip (.srt) file");
if (srtFile != null) {
srtFile.open("r");
var srtContent = srtFile.read();
srtFile.close();
code
Assistant
// Parse the SubRip file content
var entries = parseSRT(srtContent);
if (entries.length > 0) {
// Find the existing "FULL1-FIRSTHOUR" composition in the project
var mainCompName = "FULL1-FIRSTHOUR";
var mainComp = findCompByName(mainCompName);
if (mainComp == null) {
alert('The "' + mainCompName + '" composition was not found in the project.');
} else {
// Optionally adjust the mainComp's duration if needed
var mainCompDuration = Math.max(mainComp.duration, entries[entries.length - 1].endTime);
if (mainComp.duration < mainCompDuration) {
mainComp.duration = mainCompDuration;
}
var mainCompWidth = mainComp.width;
var mainCompHeight = mainComp.height;
var mainCompPixelAspect = mainComp.pixelAspect;
var mainCompFrameRate = mainComp.frameRate;
// Locate the existing compositions in the project
var whiteBG = findCompByName("WHITEBACKGROUND");
if (whiteBG == null) {
alert('The "WHITEBACKGROUND" composition was not found in the project.');
}
var windowFrameComp = findCompByName("WINDOWFRAME");
if (windowFrameComp == null) {
alert('The "WINDOWFRAME" composition was not found in the project.');
}
var animatedMaskComp = findCompByName("ANIMATEDMASK");
if (animatedMaskComp == null) {
alert('The "ANIMATEDMASK" composition was not found in the project.');
}
// Process each subtitle entry
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
// Remove "{txt}" from the text for naming
var cleanText = entry.text.replace("{txt}", "").trim();
// Calculate extra duration in seconds (11 frames at mainCompFrameRate)
var extraDuration = 11 / mainCompFrameRate;
// Calculate the subtitle duration from the SRT entry
var entryDuration = entry.endTime - entry.startTime;
// Set the comp duration to the subtitle duration plus extra 11 frames
var compDuration = entryDuration + extraDuration;
// Create a new composition for each subtitle with calculated duration
var subtitleComp = app.project.items.addComp(
cleanText,
mainCompWidth,
mainCompHeight,
mainCompPixelAspect,
compDuration,
mainCompFrameRate
);
// Add the "WINDOWFRAME" precomp first
var windowFrameLayer = null;
if (windowFrameComp != null) {
windowFrameLayer = subtitleComp.layers.add(windowFrameComp);
// Position or scale windowFrameLayer if needed
}
// Add the "WHITEBACKGROUND" precomp
var bgLayer = null;
if (whiteBG != null) {
bgLayer = subtitleComp.layers.add(whiteBG);
// Position or scale bgLayer if needed
}
// Add the text layer after the background layers so it appears on top
var textLayer = subtitleComp.layers.addText(cleanText);
var textProp = textLayer.property("Source Text");
var textDocument = textProp.value;
// Check for "{txt}" to set specific text properties
if (entry.text.indexOf("{txt}") !== -1) {
textDocument.font = "MxPlus_IBM_XGA-AI_12x20"; // Use the correct font name
textDocument.fontSize = 45;
textDocument.leading = 54;
textDocument.fillColor = hexToRgb("#24254D");
textDocument.tracking = 0;
textDocument.justification = ParagraphJustification.LEFT_JUSTIFY;
}
textProp.setValue(textDocument);
textLayer.property("Position").setValue([623, 706]);
// Precompose "WINDOWFRAME", "WHITEBACKGROUND", and text layer into "DIALOGUEBOX"
var precompLayers = [];
precompLayers.push(textLayer.index); // Text layer always exists
if (bgLayer) precompLayers.push(bgLayer.index);
if (windowFrameLayer) precompLayers.push(windowFrameLayer.index);
// Precompose the layers into "DIALOGUEBOX"
subtitleComp.layers.precompose(precompLayers, "DIALOGUEBOX", true);
// Retrieve the precomp layer by its name
var precompLayer = subtitleComp.layer("DIALOGUEBOX");
// Ensure "DIALOGUEBOX" spans the full duration
precompLayer.inPoint = 0;
precompLayer.outPoint = compDuration;
// Add "ANIMATEDMASK" on top of "DIALOGUEBOX"
if (animatedMaskComp != null) {
var animatedMaskLayer = subtitleComp.layers.add(animatedMaskComp);
// Ensure the "ANIMATEDMASK" layer is above "DIALOGUEBOX"
animatedMaskLayer.moveBefore(precompLayer);
// Set the "ANIMATEDMASK" layer to play only during the last 11 frames
animatedMaskLayer.startTime = compDuration - extraDuration;
animatedMaskLayer.inPoint = compDuration - extraDuration;
animatedMaskLayer.outPoint = compDuration;
}
// Set the track matte of "DIALOGUEBOX" to "ANIMATEDMASK" and set 'invert matte' flag
precompLayer.trackMatteType = TrackMatteType.ALPHA_INVERTED;
// Place the subtitle comp into the main comp at the correct time
var compLayer = mainComp.layers.add(subtitleComp);
compLayer.startTime = entry.startTime;
// compLayer.inPoint and outPoint are inherited from the subtitleComp duration
}
}
} else {
alert("No valid entries found in the SubRip file.");
}
}
// End undo group
app.endUndoGroup();
// Function to parse SRT content into entries
function parseSRT(data) {
var regex = /(\d+)\s+([\d:,]+)\s+-->\s+([\d:,]+)\s+([\s\S]*?)(?=\n{2,}|$)/g;
var entries = [];
var match;
code
while ((match = regex.exec(data)) !== null) {
var index = parseInt(match[1], 10);
var startTime = timeToSeconds(match[2]);
var endTime = timeToSeconds(match[3]);
var text = match[4].replace(/\r\n|\r|\n/g, "\n").trim();
entries.push({
index: index,
startTime: startTime,
endTime: endTime,
duration: endTime - startTime,
text: text
});
}
return entries;
}
// Convert time in "HH:MM:SS,ms" to seconds
function timeToSeconds(t) {
var parts = t.split(',');
var timeParts = parts[0].split(':');
var hours = parseFloat(timeParts[0]);
var minutes = parseFloat(timeParts[1]);
var seconds = parseFloat(timeParts[2]);
var milliseconds = parseFloat(parts[1]) / 1000;
// Convert hex color to RGB array (values between 0 and 1)
function hexToRgb(hex) {
var bigint = parseInt(hex.replace("#", ""), 16);
var r = ((bigint >> 16) & 255) / 255;
var g = ((bigint >> 8) & 255) / 255;
var b = (bigint & 255) / 255;
return [r, g, b];
}
// Find a composition item by name in the project panel
function findCompByName(name) {
for (var i = 1; i <= app.project.numItems; i++) {
if (app.project.item(i) instanceof CompItem && app.project.item(i).name === name) {
return app.project.item(i);
}
}
return null;
}
I want it so that when it detects more than 5 line breaks in a text, it will replace the source text from the text layer with the next lines of the .srt caption until it cannot find more than 5 line breaks.
the way it replaces is that it creates a keyframe for the "source text", when it detects more than 5 line breaks, a keyframe will be placed in the halve of the comp time with the next appropriate lines, so they change accordingly to the timestamp.
To achieve the functionality you're describing, you can modify your script to detect when the text contains more than 5 line breaks, split it accordingly, and then create keyframes for the "Source Text" property to change the text at appropriate times.
Here's how you can adjust your script:
Count the number of line breaks in the text.
If there are more than 5 line breaks, split the text into parts, each containing up to 5 lines.
Calculate the timing for the keyframes based on the duration of the composition and the number of text parts.
Set keyframes for the "Source Text" property at the calculated times, updating the text to the next part at each keyframe.
Here's the modified code snippet to replace the section where you set up the text layer and source text:
javascript
// Add the text layer after the background layers so it appears on top
var textLayer = subtitleComp.layers.addText(cleanText);
var textProp = textLayer.property("Source Text");
var textDocument = textProp.value;
// Set the initial text
textDocument.text = cleanText;
// Check for "{txt}" to set specific text properties
if (entry.text.indexOf("{txt}") !== -1) {
textDocument.font = "MxPlus_IBM_XGA-AI_12x20"; // Use the correct font name
textDocument.fontSize = 45;
textDocument.leading = 54;
textDocument.fillColor = hexToRgb("#24254D");
textDocument.tracking = 0;
textDocument.justification = ParagraphJustification.LEFT_JUSTIFY;
}
// Set the text properties at time 0
textProp.setValueAtTime(0, textDocument);
textLayer.property("Position").setValue([623, 706]);
// Now check for line breaks
var lineBreakCount = (cleanText.match(/\n/g) || []).length;
if (lineBreakCount > 5) {
// Split cleanText into lines
var lines = cleanText.split('\n');
// Split lines into parts with up to 5 lines
var parts = [];
for (var i = 0; i < lines.length; i += 5) {
var chunk = lines.slice(i, i + 5).join('\n');
parts.push(chunk);
}
var numParts = parts.length;
var interval = compDuration / numParts; // time between each change
// Set keyframes for each part
for (var j = 0; j < numParts; j++) {
var currentTime = j * interval;
// Create a new TextDocument with the current part
var textDocCopy = new TextDocument(parts[j]);
// Assign text properties
if (entry.text.indexOf("{txt}") !== -1) {
textDocCopy.font = textDocument.font;
textDocCopy.fontSize = textDocument.fontSize;
textDocCopy.leading = textDocument.leading;
textDocCopy.fillColor = textDocument.fillColor;
textDocCopy.tracking = textDocument.tracking;
textDocCopy.justification = textDocument.justification;
}
// Set keyframe at the current time
textProp.setValueAtTime(currentTime, textDocCopy);
}
} else {
// Text is already set at time 0, no further action needed
}
Explanation:
Counting Line Breaks: The script uses a regular expression to count the number of line breaks (\n) in cleanText.
javascript
var lineBreakCount = (cleanText.match(/\n/g) || []).length;
Splitting the Text: If there are more than 5 line breaks, it splits the text into an array of lines and then groups these lines into chunks of up to 5 lines each.
javascript
var lines = cleanText.split('\n');
// Split lines into parts with up to 5 lines
var parts = [];
for (var i = 0; i < lines.length; i += 5) {
var chunk = lines.slice(i, i + 5).join('\n');
parts.push(chunk);
}
Calculating Keyframe Intervals: The script calculates the interval between keyframes based on the composition's duration and the number of text parts.
javascript
var numParts = parts.length;
var interval = compDuration / numParts;
Setting Keyframes: For each part, the script creates a new TextDocument, sets the necessary properties, and then sets a keyframe for the "Source Text" property at the calculated time.
javascript
for (var j = 0; j < numParts; j++) {
var currentTime = j * interval;
var textDocCopy = new TextDocument(parts[j]);
// Assign text properties
// ...
textProp.setValueAtTime(currentTime, textDocCopy);
}
This adjustment ensures that:
The text changes at equal intervals throughout the duration of the composition.
Each displayed text segment contains no more than 5 lines.
The text properties (font, size, color, etc.) remain consistent across all text segments.
Notes:
TextDocument Copying: Since the TextDocument object may not support cloning directly, the script creates a new TextDocument for each keyframe and manually copies over the necessary properties.
Keyframe Timing: The keyframes are placed at times 0, interval, 2 * interval, etc., ensuring that the text changes smoothly over the composition's duration.
Animated Mask and Other Layers: The rest of your script remains the same, ensuring that the animated mask and other layers function as intended.
By incorporating this code into your script, you'll achieve the desired effect where long texts are broken up and displayed sequentially, with the "Source Text" property updating via keyframes during the composition's duration.