Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

I have the following After Effects extendscript: // ExtendScript for After Effects //…

  1. User

    I have the following After Effects extendscript:

    // ExtendScript for After Effects

    // Begin undo group for script actions app.beginUndoGroup("Create SubRip Comps");

    // 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) {
        // Create a main composition to hold all subtitle comps
        var mainCompName = "Subtitles_Comp";
        var mainCompDuration = entries[entries.length - 1].endTime;
        var mainCompWidth = 1920;
        var mainCompHeight = 1080;
        var mainCompPixelAspect = 1.0;
        var mainCompFrameRate = 30; // Adjust as needed
    
        var mainComp = app.project.items.addComp(
            mainCompName,
            mainCompWidth,
            mainCompHeight,
            mainCompPixelAspect,
            mainCompDuration,
            mainCompFrameRate
        );
    
        // Locate the existing "WHITEBACKGROUND" shape layer in the project
        var whiteBG = findFootageByName("WHITEBACKGROUND");
        if (whiteBG == null) {
            alert('The "WHITEBACKGROUND" layer 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();
    
            // Create a new composition for each subtitle
            var subtitleComp = app.project.items.addComp(
                cleanText,
                mainCompWidth,
                mainCompHeight,
                mainCompPixelAspect,
                entry.duration,
                mainCompFrameRate
            );
    
            // Add the text layer
            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"; // Ensure this font is installed
                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]);
    
            // Add the "WHITEBACKGROUND" layer beneath the text layer
            if (whiteBG != null) {
                var bgLayer = subtitleComp.layers.add(whiteBG);
                bgLayer.moveBefore(textLayer);
            }
    
            // Place the subtitle comp into the main comp at the correct time
            var compLayer = mainComp.layers.add(subtitleComp);
            compLayer.startTime = entry.startTime;
            compLayer.inPoint = 0;
            compLayer.outPoint = entry.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 footage item by name in the project panel function findFootageByName(name) { for (var i = 1; i <= app.project.numItems; i++) { if (app.project.item(i) instanceof FootageItem && app.project.item(i).name === name) { return app.project.item(i); } } return null; }

    but when I run it, I get "Unable to execute script at line 105. Function match[4].replace().trim is undefined". how do I fix this?

  2. Assistant

    The error you're encountering, "Unable to execute script at line 105. Function match[4].replace().trim is undefined," occurs because the trim() method is not available in the version of JavaScript that ExtendScript uses for scripting in After Effects. ExtendScript is based on an older version of JavaScript (similar to ECMAScript 3), which doesn't include String.prototype.trim() or Array.prototype.indexOf(), among other modern methods.

    To fix this issue, you need to provide a polyfill for the trim() method—that is, a custom function that adds trim() functionality if it's missing. Here's how you can do it:

    Step 1: Define the trim() function if it doesn't exist

    Add the following code at the very beginning of your script (before any other code):

    if (typeof String.prototype.trim !== 'function') {
        String.prototype.trim = function() {
            return this.replace(/^\s+|\s+$/g, '');
        };
    }
    

    This code checks if trim() is not a function on String.prototype, and if not, it defines it. The custom trim() function uses a regular expression to remove whitespace from the start and end of the string, effectively trimming it.

    Step 2: Replace any other unsupported methods if needed

    Similarly, if you use other modern JavaScript methods that are not available in ExtendScript, you should provide polyfills for them. For example, if you use Array.prototype.forEach(), you might need to define it as well.

    Why This Works:

    By defining trim() when it's not available, you ensure that your script can use trim() as if it were a standard method. This fix is minimal and doesn't require you to change other parts of your code.

    Updated Script Snippet:

    Here's how the beginning of your script should look after adding the polyfill:

    // 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");
    
    // ... rest of your script ...
    

    Note: Ensure that you place the polyfill code before any other code that might use trim().

    Alternative Solution:

    If you prefer not to modify the String.prototype, you can create a helper function and use it wherever needed:

    function trimString(str) {
        return str.replace(/^\s+|\s+$/g, '');
    }
    

    Then, replace instances of .trim() with trimString(). For example:

    var text = trimString(match[4].replace(/\r\n|\r|\n/g, "\n"));
    

    However, the first solution (adding trim() to String.prototype) is often more straightforward, especially if trim() is used in multiple places in your script.

    Conclusion:

    By adding this polyfill, your script should run without encountering the trim() undefined error. Remember that when working with ExtendScript, you may need to account for missing modern JavaScript features due to its reliance on an older version of the language.


    References:


    Final Note: Always test your script after making these changes to ensure that it works correctly in your specific environment.

    Answer: Because ExtendScript lacks the string trim() function, you can fix this by adding code to define trim()—add this near the top of your script:

    if (typeof String.prototype.trim !== 'function') {
        String.prototype.trim = function() {
            return this.replace(/^\s+|\s+$/g, '');
        };
    }