// 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;
}
Please add a feature where if it detects more than 6 line breaks from a message, it will switch the text from the text layer from the first 6 lines to the next 6 lines
Certainly! To add the feature where if the script detects more than 6 line breaks in a text entry, it will switch the text from the first 6 lines to the next 6 lines during the subtitle's duration, we need to modify the part of the script where the text layer is created and set.
Here's how you can modify your script to achieve this:
Split the text into lines: We'll split the text into an array of lines based on the line breaks.
Group lines into chunks of 6: We'll create an array where each element contains up to 6 lines of text.
Determine the duration for each chunk: We'll divide the total duration of the subtitle by the number of chunks to determine how long each chunk should display.
Set keyframes to switch the text: We'll set keyframes on the text layer's Source Text property to switch between chunks at the calculated times.
Below is the modified section of your script with the necessary changes. Look for the comments indicating the modifications.
javascript
// ... [Rest of your script above remains the same] ...
// 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;
// Apply text properties if "{txt}" is found in the entry text
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;
}
// [Modification Start]
// Split the text into lines
var lines = cleanText.split('\n');
// Create an array of line blocks (chunks of up to 6 lines)
var lineBlocks = [];
for (var l = 0; l < lines.length; l += 6) {
lineBlocks.push(lines.slice(l, l + 6).join('\n'));
}
// Determine the duration per block
var numBlocks = lineBlocks.length;
var blockDuration = compDuration / numBlocks;
// Set keyframes for each block
for (var n = 0; n < numBlocks; n++) {
var time = n * blockDuration;
var newTextDocument = new TextDocument(lineBlocks[n]);
// Apply the same formatting properties
newTextDocument.font = textDocument.font;
newTextDocument.fontSize = textDocument.fontSize;
newTextDocument.leading = textDocument.leading;
newTextDocument.fillColor = textDocument.fillColor;
newTextDocument.tracking = textDocument.tracking;
newTextDocument.justification = textDocument.justification;
textProp.setValueAtTime(time, newTextDocument);
}
// [Modification End]
// Position the text layer
textLayer.property("Position").setValue([623, 706]);
// ... [Rest of your script below remains the same] ...
Explanation of the Modifications:
Splitting the Text into Lines:
javascript
var lines = cleanText.split('\n');
This splits the cleaned text into an array of lines based on the newline character.
Creating Line Blocks:
javascript
var lineBlocks = [];
for (var l = 0; l < lines.length; l += 6) {
lineBlocks.push(lines.slice(l, l + 6).join('\n'));
}
This groups the lines into chunks, each containing up to 6 lines. If there are 7-12 lines, it will create two blocks: the first with lines 1-6 and the second with lines 7-12.
Determining Block Duration:
javascript
var numBlocks = lineBlocks.length;
var blockDuration = compDuration / numBlocks;
This calculates how long each block should be displayed by dividing the composition's duration by the number of blocks.
Setting Keyframes to Switch Text:
javascript
for (var n = 0; n < numBlocks; n++) {
var time = n * blockDuration;
var newTextDocument = new TextDocument(lineBlocks[n]);
// Apply the same formatting properties
newTextDocument.font = textDocument.font;
newTextDocument.fontSize = textDocument.fontSize;
newTextDocument.leading = textDocument.leading;
newTextDocument.fillColor = textDocument.fillColor;
newTextDocument.tracking = textDocument.tracking;
newTextDocument.justification = textDocument.justification;
textProp.setValueAtTime(time, newTextDocument);
}
This loop sets keyframes on the Source Text property at the calculated times, switching the text to the next block of lines. A new TextDocument is created for each block to avoid overwriting previous keyframes, and the formatting properties are copied over to ensure consistent styling.
Notes:
Handling More Than 12 Lines:
The script will handle any number of lines, dividing them into chunks of 6. So if there are more than 12 lines, it will continue creating additional blocks and keyframes.
Text Formatting Consistency:
By copying the formatting properties to each new TextDocument, we ensure that the text styling remains consistent across all keyframes.
Timing of Text Switches:
The text switches are evenly distributed throughout the duration of the subtitle composition. If you want to customize the timing (e.g., show the first block for longer), you can adjust the blockDuration calculation or set custom times in the loop.
Complete Modified Script Section:
Make sure to replace the corresponding section in your original script with the modified one above.
Testing the Changes:
After making the modifications, test the script with SRT files that have entries containing more than 6 lines to ensure that the text switches correctly during the subtitle's duration.
This modification adds the requested feature to your script, allowing it to handle subtitles with more than 6 lines by switching the displayed text during the composition's duration.