I have the following AfterEffects extendscript: // Polyfill for String.trim() in…
- User
I have the following AfterEffects extendscript:
// 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();
// 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(); // Set the comp duration to 11 frames var compDuration = 11 / mainCompFrameRate; // Create a new composition for each subtitle with duration of 11 frames 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 = []; if (windowFrameLayer) precompLayers.push(windowFrameLayer.index); if (bgLayer) precompLayers.push(bgLayer.index); precompLayers.push(textLayer.index); // Text layer always exists // Sort the layer indices in ascending order precompLayers.sort(function(a, b) { return a - b; }); // Precompose the layers and get the index of the new layer var precompLayerIndex = subtitleComp.layers.precompose(precompLayers, "DIALOGUEBOX", true); // Retrieve the precomp layer using the index var precompLayer = subtitleComp.layer(precompLayerIndex); // 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 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; // No need to set inPoint and outPoint; it will inherit from the comp's 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;
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;
return hours * 3600 + minutes * 60 + seconds + milliseconds;}
// 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; }
When I run it, I get the following error: Unable to execute script at line 128. After Effects error: Unable to call "moveBefore" because of parameter 1. null is not of the correct type." how would I fix this?
- Assistant
The error you're encountering occurs because
precompLayerisnullwhen you try to use it as an argument inanimatedMaskLayer.moveBefore(precompLayer). This happens due to an issue with how the precomposed layer is retrieved after precomposition.Here's how to fix it:
-
Remove the sorting of
precompLayers:The order of layer indices should be from topmost to bottommost layers (i.e., from the lowest index to the highest index). Since layers are added to the top of the stack in After Effects (layer index
1being the topmost), you should collect the layer indices without sorting them.// Collect layer indices without sorting var precompLayers = []; precompLayers.push(textLayer.index); // Text layer always exists if (bgLayer) precompLayers.push(bgLayer.index); if (windowFrameLayer) precompLayers.push(windowFrameLayer.index); -
Retrieve the precomp layer by name instead of index:
The
precomposemethod doesn't always return the expected layer index, especially when layers are dynamically added or if layers are missing. To reliably get the precomp layer, retrieve it by its name after precomposing.// Precompose the layers subtitleComp.layers.precompose(precompLayers, "DIALOGUEBOX", true); // Retrieve the precomp layer by its name var precompLayer = subtitleComp.layer("DIALOGUEBOX"); -
Update the rest of your code accordingly:
With these changes, your
moveBeforemethod will have a validprecompLayer, and the script should execute without errors.
Revised Code Snippet Around the Error:
// Precompose the layers into "DIALOGUEBOX" var precompLayers = []; precompLayers.push(textLayer.index); // Text layer always exists if (bgLayer) precompLayers.push(bgLayer.index); if (windowFrameLayer) precompLayers.push(windowFrameLayer.index); // No need to sort the layer indices // Precompose the layers subtitleComp.layers.precompose(precompLayers, "DIALOGUEBOX", true); // Retrieve the precomp layer by its name var precompLayer = subtitleComp.layer("DIALOGUEBOX"); // 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 track matte of "DIALOGUEBOX" to "ANIMATEDMASK" and set 'invert matte' flag precompLayer.trackMatteType = TrackMatteType.ALPHA_INVERTED;Explanation:
-
Layer Indices: Removing the sorting ensures the layers are precomposed in the correct order. Since layers are stacked from the top down (with index
1at the top), the indices should be collected in the order the layers are intended to be in the precomp. -
Retrieving the Precomp Layer: By retrieving the precomp layer by its name ("DIALOGUEBOX"), you eliminate the uncertainty of layer indices shifting after precomposition, ensuring
precompLayeris notnull.
Note:
Always ensure that layer names are unique within the composition to prevent conflicts when retrieving layers by name.
-