Post on 07-Apr-2018
8/6/2019 Gua scripting
1/209
8/6/2019 Gua scripting
2/209
Copyright 2005 Adobe Systems Incorporated. Todos los derechos reservados.
Gua de secuencias de comandos de Adobe After Effects
AVISO: Toda la informacin contenida en este documento es propiedad de Adobe Systems Incorporated. Se prohbe reproducir y transmitir
cualquier parte de esta publicacin (ya sea en formato impreso o electrnico) en cualquier forma o por cualquier medio (electrnico,
mecnico, fotocopiado, grabacin o de otro tipo) sin el previo consentimiento por escrito de Adobe Systems Incorporated. El software
descrito en este documento se proporciona bajo licencia y slo puede utilizarse o copiarse de acuerdo con los trminos de dicha licencia.
Esta publicacin y la informacin que contiene se proporciona TAL CUAL, est sujeta a cambios sin previo aviso y no debe interpretarse como
un compromiso por parte de Adobe Systems Incorporated. Adobe Systems Incorporated no asume ninguna responsabilidad ni compromiso
por errores o inexactitudes, no ofrece garanta de ningn tipo (ya sean expresas, implcitas o legales) respecto a esta publicacin y niegaexpresamente todas las garantas de comerciabilidad, adaptacin para un propsito particular y no-infraccin de derechos de terceros.
Cualquier referencia a nombres de empresas en las plantillas de ejemplo tiene slo fines informativos y no pretende referirse a ninguna
organizacin real.
Adobe, el logotipo de Adobe, After Effects y Photoshop son marcas comerciales o marcas registradas de Adobe Systems Incorporated en
Estados Unidos y en otros pases.
Apple, Mac y Macintosh son marcas comerciales de Apple Computer, Inc., registradas en Estados Unidos y en otros pases. Microsoft y
Windows son marcas comerciales o marcas registradas de Microsoft Corporation en Estados Unidos y en otros pases. JavaScript y todas las
marcas relativas a Java son marcas comerciales o marcas registradas de Sun Microsystems, Inc. en Estados Unidos y en otros pases. UNIX es
una marca registrada de The Open Group. Cualquier otra marca comercial es propiedad de sus propietarios respectivos.
Cualquier otra marca comercial es propiedad de sus propietarios respectivos.
Si esta gua se distribuye con software que incluye un contrato de licencia de usuario final, la gua, as como el software que en ella sedescribe, se proporcionan bajo licencia y pueden utilizarse o copiarse slo de acuerdo con los trminos de dicha licencia. Exceptuando lo
permitido por tal licencia, se prohbe reproducir, almacenar en un sistema de recuperacin o transmitir cualquier parte de esta gua, en
cualquier forma o por cualquier medio, ya sea electrnico, mecnico, en grabacin o de otra forma, sin el previo consentimiento por escrito
por parte de Adobe Systems Incorporated. Tenga en cuenta que el contenido de esta gua est protegido por leyes de derechos de autor
(copyright), aunque no se distribuya con software que incluya un contrato de licencia de usuario final.
El contenido de esta gua se proporciona slo con fines informativos, est sujeto a cambios sin previo aviso y no debe interpretarse como un
compromiso por parte de Adobe Systems Incorporated. Adobe Systems Incorporated no asume ninguna responsabilidad o compromiso por
errores o inexactitudes que puedan aparecer en el contenido informativo de esta gua.
Adobe Systems Incorporated, 345 Park Avenue, San Jos, California 95110, EE.UU.
8/6/2019 Gua scripting
3/209
3
Introduccin
La Gua de secuencias de comandos de After Effects muestra cmo obtener un control de los procedimientos de
los proyectos de After Effects mediante secuencias de comandos. Este conjunto de funciones est disponible
nicamente en Adobe After Effects 7.0 Professional Edition.
Mediante las secuencias de comandos del sistema, puede simplificar la canalizacin de procesos y evitar tener
que seleccionar y hacer clic repetidamente. Si ha utilizado expresiones u otras tcnicas similares a JavaScript
para la animacin, o ha trabajado con secuencias de comandos del sistema en AppleScript o Visual Basic,
reconocer la eficacia de las secuencias de comandos en After Effects. Con prctica y experiencia suficiente en
el lenguaje JavaScript, podr controlar la canalizacin de los grficos.
Automatizacin de procesos
Uno de los usos principales de las secuencias de comandos en After Effects 7.0 es la automatizacin de procesos.
Interesar a cualquier persona responsable de administrar una canalizacin de procesos compleja.
La automatizacin de procesos se puede llevar a cabo mediante secuencias de comandos codificadas
manualmente o mediante una solucin de procesamiento en red de terceros que admita la administracin
automatizada de las canalizaciones de procesos en red.
Adems de las soluciones de secuencias de comandos, After Effects proporciona una herramienta de lnea de
comandos para la automatizacin de procesos. Esta herramienta, aerender , permite procesar composiciones
desde la lnea de comandos, sin pasar por la interfaz de usuario de After Effects. Para obtener informacin dereferencia completa sobre esta herramienta, consulte Render Automation Command en la pgina 207.
Si no est familiarizado con las secuencias de comandos
After Effects 7.0 es una herramienta visual con una interfaz de usuario grfica; est acostumbrado a interactuar
con ella mediante elementos de la interfaz, como mens, paneles e iconos. Para la mayor parte, sta es la
manera ms asequible de trabajar. Las secuencias de comandos estn diseadas para situaciones en las que
esta metodologa conlleva numerosas repeticiones o laboriosas bsquedas y ordenaciones que se pueden
automatizar. Las secuencias de comandos son un mtodo abreviado para tareas tediosas que, de otra manera,
exigen seleccionar y hacer clic muchas veces. Tambin resultan tiles para aprovechar la eficacia del
procesamiento en red en situaciones en las que la Carpeta de inspeccin es menos eficaz (y ms difcil deconfigurar). Consulte Examples en la pgina 167 para ver ejemplos de lo que hacen las secuencias de comandos.
Las secuencias de comandos estn disponibles incluso para usuarios no interesados en aprender a utilizar el
lenguaje JavaScript. Si usted es este tipo de usuario, an puede aprovechar la eficacia de las secuencias de
comandos mediante soluciones de terceros como Rush Network Render Queue, una interfaz de usuario grfica
que permite configurar procesos distribuidos desde cualquier equipo de la red sin tener que configurarlos en
equipos individuales.
Uno de los usos principales de las secuencias de comandos en After Effects 7.0 es la automatizacin de procesos.
Adems de la interfaz de secuencias de comandos, After Effects ofrece una herramienta de lnea de comandos,
aerender , especial para este fin (consulte Render Automation Command en la pgina 207).
8/6/2019 Gua scripting
4/209
4
Gua de secuencias de comandos de After Effects Introduccin
4
Tambin puede aprovechar la contribucin de usuarios que comparten secuencias de comandos con otros
usuarios. Los grandes estudios pueden tener a estos usuarios en plantilla, mientras que otros usuarios pueden
visitar foros como los que encontrar en
www.adobeforums.com .
Objetos de After Effects
Es posible que no considere After Effects como un conjunto de objetos jerrquicos, pero cuando utiliza
elementos de la cola de procesamiento, composiciones y proyectos, as es cmo aparecern en las secuencias
de comandos. Al igual que las funciones de expresiones en After Effects permiten el acceso prcticamente a
cualquier propiedad de cualquier capa en una composicin del proyecto (a cada una de las cuales llamamos
objeto) , las secuencias de comandos permiten el acceso a la jerarqua de objetos de After Effects y la realizacin
de cambios en estos objetos.
Las secuencias de comandos de After Effects estn basadas en ECMAScript (o ms concretamente,
la tercera edicin de la norma ECMA-262). Puede obtener documentacin adicional sobre este estndar
en www.ecma-international.org.
Expresiones y matemtica del movimiento
Puesto que las secuencias de comandos tienen acceso a propiedades de capas individuales y utilizan JavaScript,
se puede suponer que las expresiones y las secuencias de comandos son lo mismo. Pero son dos entidades
totalmente distintas. Las expresiones no pueden tener acceso a informacin de las secuencias de comandos
(como variables y funciones), mientras que una secuencia de comandos puede crear o editar una expresin.
No obstante, la similitud entre las expresiones y las secuencias de comandos reside en que se crean con el
mismo lenguaje, la norma ECMA de JavaScript. Por tanto, saber cmo se utilizan unas es til para entender
las otras.
La matemtica del movimiento ya no se incluye en After Effects; su funcionalidad ha sido reemplazada por
las secuencias de comandos y las expresiones. Todos los operadores matemticos y lgicos comunes para
ECMAScript estn disponibles en las secuencias de comandos.
Por ejemplo, con expresiones se puede simular la fsica de una pelota que bota mediante la aplicacin de reglas
matemticas a una capa pelota. Pero con secuencias de comandos, se puede crear una interfaz de usuario
completa que permita la animacin de una capa de una pelota que bota y su sombra utilizando los criterios
que especifica el usuario.
Acerca de esta gua
Esta gua est destinada a usuarios que administren canalizaciones de grficos (que pueden incluir tambin
otras aplicaciones de secuencias de comandos) y que deseen escribir secuencias de comandos que agreguen
capacidades personalizadas a After Effects.
Esta funcionalidad tambin la ofrecen soluciones de administracin de procesos en red de terceros. Estos
productos incluyen software diseado para facilitar la administracin de este proceso, por lo que es posible
aprovechar la funcionalidad sin necesidad de editar manualmente las secuencias de comandos.
Aunque esta gua est destinada a proporcionar informacin sobre las extensiones que se han agregado al
lenguaje ECMAScript/JavaScript para la aplicacin de secuencias de comandos a proyectos de After Effects,
para aprovechar al mximo las posibilidades de las secuencias de comandos necesitar saber cmo escribirlas
en el nivel del sistema (para la integracin con AppleScript o la lnea de comandos Terminal en Mac OS y las
secuencias de comandos de la lnea de comandos en Windows) y tener nociones bsicas sobre JavaScript.
8/6/2019 Gua scripting
5/209
5
Gua de secuencias de comandos de After Effects Introduccin
5
Las secuencias de comandos reproducen gran parte de lo que se puede hacer mediante la interfaz de usuario
de After Effects, por lo que es fundamental tener un slido conocimiento de la aplicacin para saber cmo
utilizar esta funcionalidad.
NOTA: Los objetos de JavaScript llamados normalmente propiedades reciben el nombre de atributos en esta
gua para evitar la confusin con la propia definicin de una propiedad en After Effects (un valor que se puede
animar de un efecto, mscara o transformacin en una capa individual).
Activacin de funciones de secuencias de comandos completas
Por motivos de seguridad, las funciones de secuencias de comandos que se ejecutan fuera de la aplicacin After
Effects (como agregar y eliminar archivos y carpetas en volmenes, o el acceso a la red) estn deshabilitadas
de forma predeterminada.
Para habilitar estas funciones, elija Preferencias > General y seleccione Permitir que los scripts puedan
escribir archivos y acceder a la red.
Al seleccionar esta opcin, permitir lo siguiente:
Escribir archivos
Crear carpetas
Definir la carpeta actual
Crear un socket
Abrir un socket
Escuchar un socket
El kit de herramientas de ExtendScript (un depurador de JavaScript) est deshabilitado de forma
predeterminada para que los usuarios que no lo van a utilizar no lo encuentren. Al editar o escribir secuencias
de comandos, el kit de herramientas ayuda a detectar problemas relativos a secuencias de comandos. Para
activar el kit de herramientas en el equipo local cuando se produzca un error de una secuencia de comandos,elija Preferencias > General y seleccione Activar el depurador de JavaScript. Para obtener informacin
detallada sobre el kit de herramientas de ExtendScript, consulte laBridge JavaScript Reference.
Tenga en cuenta que el kit de herramientas se inicia slo cuando se ejecuta una secuencia de comandos, no
con expresiones, aunque stas tambin utilicen JavaScript.
Acceso y escritura de secuencias de comandos
Para crear y editar secuencias de comandos para After Effects, puede utilizar el kit de herramientas de
ExtendScript o una aplicacin de edicin de texto externa que permita crear archivos con la codificacin de
texto Unicode UTF-8. Tenga cuidado con aplicaciones como Microsoft Word, que de forma predeterminada
agregan informacin de encabezado a los archivos; estas aplicaciones crean errores de lnea 0 en las secuenciasde comandos y provocan un fallo de ejecucin.
Una secuencia de comandos puede residir en cualquier lugar, pero para que se muestre en el men Scripts es
necesario que se guarde en la carpeta Scripts, dentro de la carpeta de la aplicacin After Effects. Para obtener
ms informacin sobre cmo escribir y modificar secuencias de comandos, consulte Escritura de secuencias
de comandos en la pgina 6.
No hay un mtodo integrado de grabar una serie de acciones en una secuencia de comandos en After Effects
del modo en que se realiza en Photoshop. Las secuencias de comandos se crean fuera de After Effects y se
ejecutan dentro, o externamente mediante una lnea de comandos, el kit de herramientas de ExtendScript o
el software de administracin de procesos de terceros.
8/6/2019 Gua scripting
6/209
6
Escritura de secuencias de comandos
Cuando utiliza Adobe After Effects, crea proyectos, composiciones y elementos de la cola de procesamiento
junto con todos los elementos que contienen: material de archivo, imgenes, slidos, capas, mscaras, efectos
y propiedades. En trminos de secuencia de comandos, cada uno de estos elementos es un objeto.
El ncleo de una aplicacin de secuencia de comandos es el modelo de objetos. En After Effects, el modelo
de objetos est formado por un proyecto, elementos, composiciones, capas y elementos de la cola de
procesamiento. Cada objeto tiene sus atributos especiales y cada objeto de un proyecto de After Effects
tiene una identidad propia (aunque no todos se pueden utilizar con secuencias de comandos).
Debe estar familiarizado con el modelo de objetos de After Effects para poder crear secuencias de comandos.
Si desea conocer ms recursos para aprender a utilizar secuencias de comandos, consulte Ms recursos para
aprender a utilizar secuencias de comandos en la pgina 9.
Edicin de secuencias de comandos
After Effects 7.0 incluye un editor de JavaScript. Para iniciarlo, elija Archivo > Scripts > Abrir el Editor de
secuencias de comandos. Este depurador y editor de secuencias de comandos, llamado Kit de herramientas de
ExtendScript, proporciona una cmoda interfaz para crear y probar sus propias secuencias de comandos.
Puede utilizar cualquier editor de texto para crear, editar y guardar secuencias de comandos, pero se
recomienda que elija una aplicacin que no agregue automticamente informacin de encabezado al guardar
los archivos y que guarde con la codificacin Unicode (UTF-8).
Algunas aplicaciones de Windows tiles para editar secuencias de comandos son EM Editor o el Bloc de
notas integrado (asegrese de definir la codificacin como UTF-8 en las opciones de guardar).
Entre las aplicaciones de Mac OS tiles para editar secuencias de comandos se incluyen BBEdit o la
aplicacin integrada OS X TextEdit (asegrese de definir el t ipo de almacenamiento como Unicode [UTF-
8] en las preferencias).
Formato JSX de ExtendScript
After Effects admite ExtendScript, la implementacin extendida de JavaScript de Adobe. Todas las aplicaciones
de Adobe que proporcionan una interfaz de secuencias de comandos utilizan ExtendScript. Adems de
implementar el lenguaje JavaScript segn la especificacin ECMA 2.6.2, ExtendScript ofrece funciones y
utilidades adicionales:
Kit de herramientas de ExtendScript: Como ayuda para crear, depurar y probar secuencias de comandos,
ExtendScript proporciona un entorno de desarrollo y de prueba interactivo, el Kit de herramientas de
ExtendScript. Tambin define un objeto de depuracin global, el objeto de dlar ($) y una utilidad de
generacin de informes para elementos de ExtendScript, la interfaz ExtendScript Reflection.
Objetos File y Folder: Puesto que la sintaxis de los nombres de rutas es muy diferente en los distintos sistemas
operativos, Adobe ExendScript define los objetos File y Folder para proporcionar un acceso independiente de
la plataforma al sistema de archivos subyacente.
8/6/2019 Gua scripting
7/209
7
Gua de secuencias de comandos de After Effects Escritura de secuencias de comandos
7
Mdulo de interfaz de usuario ScriptUI: El mdulo ScriptUI de ExtendScript permite crear e interactuar con
elementos de la interfaz de usuario. ScriptUI proporciona un modelo de objetos para ventanas y elementos de
control de UI en una aplicacin de Adobe.
NOTA: After Effects no admite la personalizacin de la funcin de diseo automtico de ScriptUI.
Herramientas y utilidades: Adems, ExtendScript ofrece herramientas y funciones, como una utilidad detraduccin que proporciona valores de cadenas de la interfaz de usuario en distintos idiomas y funciones
globales para mostrar mensajes cortos en cuadros de dilogo (alert , confirm y prompt ).
Comunicacin entre aplicaciones: ExtendScript proporciona un entorno de secuencias de comandos comn
para todas las aplicaciones de Adobe y permite la comunicacin entre aplicaciones mediante secuencias de
comandos.
Estas funciones se describen en detalle enBridge JavaScript Reference, disponible con After Effects.
Los archivos de secuencias de comandos de ExtendScript se diferencian por la extensin .jsx, una variacin de
la extensin estndar . js utilizada con los archivos de JavaScript. Las secuencias de comandos de After Effects
deben incluir la extensin de archivo .jsx para que la aplicacin las reconozca correctamente. Cualquier
archivo de texto codificado con UTF-8 que tenga la extensin .jsx se reconocer como un archivo de
ExtendScript.
Men y carpeta Scripts
Las secuencias de comandos de After Effects residen en la carpeta Scripts, dentro de la misma carpeta que el
archivo de la aplicacin After Effects 7.0. Cuando se inicia la aplicacin, slo las secuencias de comandos
guardadas en esta carpeta Scripts se enumeran automticamente en el men Scripts, aunque los archivos de
secuencias de comandos pueden residir en cualquier lugar.
Para ejecutar una secuencia de comandos que no aparece en el men Scripts, elija Archivo > Scripts > Ejecutar
guin y seleccione la secuencia de comandos en el cuadro de dilogo Abrir. Tambin puede enviar a After
Effects una secuencia de comandos desde el Kit de herramientas de ExtendScript, la lnea de comandos
(en Windows) o AppleScript (en Mac OS).
Para que se muestre en el cuadro de dilogo Abrir, la secuencia de comandos debe incluir la extensin de
archivo .jsx adecuada.
Carpetas Shutdown y Startup
La carpeta Scripts contiene dos carpetas llamadas Startup y Shutdown. After Effects ejecuta automticamente
las secuencias de comandos guardadas en estas carpetas, en orden alfabtico, al iniciar y cerrar la aplicacin,
respectivamente.
En la carpeta Startup puede colocar las secuencias de comandos que desea que se ejecuten al iniciar la
aplicacin. Se ejecutarn despus de que se inicialice la aplicacin y todos los plugins estn cargados.
Las secuencias de comandos comparten un entorno global, de manera que cualquier secuencia que se ejecuteal inicio puede definir variables y funciones disponibles para todas las secuencias de comandos. En todos los
casos, las variables y las funciones, una vez definidas mediante la ejecucin de la secuencia de comandos que
las contiene, continan en las siguientes secuencias de comandos durante una sesin de After Effects
especfica. Cuando se cierra la aplicacin, todas estas variables y funciones definidas globalmente se eliminan.
Los creadores de secuencias de comandos deben tener precaucin a la hora de asignar nombres nicos a las
variables incluidas en secuencias, de manera que una secuencia de comandos no vuelva a asignar por
equivocacin variables globales destinadas a continuar durante toda una sesin.
Tambin se pueden agregar atributos a objetos existentes, como el objeto Application (consulte Application
object en la pgina 19), para extender la aplicacin a otras secuencias de comandos.
8/6/2019 Gua scripting
8/209
8
Gua de secuencias de comandos de After Effects Escritura de secuencias de comandos
8
Las secuencias de comandos guardadas en la carpeta Shutdown se ejecutan cuando se cierra la aplicacin. Esto
se produce despus de cerrar el proyecto pero antes de que se cierre otra aplicacin.
Envo de secuencias de comandos a After Effects desde el sistema
Si est familiarizado con la ejecucin de secuencias de comandos desde la lnea de comandos en Windows o
mediante AppleScript, puede enviar una secuencia directamente a la aplicacin After Effects abierta, que
despus se ejecutar automticamente.
Cmo incluir secuencias de comandos de After Effects en una lnea de comandos (Windows)
A continuacin se indican algunos ejemplos de entradas de la lnea de comandos de Windows que envan una
secuencia de comandos de After Effects a la aplicacin sin utilizar la interfaz de usuario de After Effects para
ejecutarla.
En el primer ejemplo, se copia y pega la secuencia de comandos de After Effects directamente en la lnea
de comandos y despus se ejecuta. El texto de la secuencia aparecer entre comillas despus del comando
afterfx.exe s:afterfx.exe s "alert("Acaba de enviar una alerta a After Effects")"
Tambin puede especificar la ubicacin del archivo JSX que se va a ejecutar. Por ejemplo:
afterfx .exe r c: \misDocumentos\Scripts \suAEScriptH ere. jsx
afterfx .exe r "c:\misDocum entos\Scripts \Nombre de Script con Spaces . jsx"
Cmo incluir secuencias de comandos de After Effects en AppleScript (Mac OS)
A continuacin se indican tres ejemplos de AppleScript que envan un archivo JSX que contiene una secuencia
de comandos de After Effects a la aplicacin sin utilizar la interfaz de usuario de After Effects para ejecutarla.
En el primer ejemplo, se copia la secuencia de comandos de After Effects directamente en AppleScript ydespus se ejecuta. El texto de la secuencia aparecer entre comillas despus del comando DoScript, de manera
que deben omitirse las comillas internas de la secuencia con el carcter de escape de barra invertida, como se
muestra a continuacin:
tell application "Adobe After Effects 7.0"
DoScript "alert( \"Acaba de enviar u na alert a a After Effects \")"
end tel l
Tambin puede mostrar un cuadro de dilogo que pida la ubicacin del archivo JSX que se va a ejecutar,
de la siguiente manera:
set theFile to choo se file
tell application "Adobe After Effects 7.0"
DoScript theFile
end tel l
Por ltimo, esta secuencia de comandos es quiz la ms til cuando se trabaja directamente en la edicin de
una secuencia de comandos JSX y se desea enviarla a After Effects para probarla o ejecutarla. Para utilizarla de
manera eficaz, debe especificar la aplicacin que contiene el archivo JSX abierto (en este ejemplo, TextEdit);
si no sabe el nombre exacto de la aplicacin, escriba lo ms parecido a TextEdit y AppleScript le pedir que
la busque.
8/6/2019 Gua scripting
9/209
9
Gua de secuencias de comandos de After Effects Escritura de secuencias de comandos
9
Basta con que resalte el texto de la secuencia que desea ejecutar y, a continuacin, active este AppleScript:
( *
Esta secuencia de coman dos enva la seleccin actual a After Effects como un a secuencia de comand os.
*)
tell application TextEdit
set the_script t o select ion as text
end tel l
tell application "Adobe After Effects 7.0"
act ivate
DoScript t he_script
end tel l
Para obtener ms informacin sobre cmo utilizar AppleScript, consulteAppleScript: the Definitive Guide de
Matt Neuberg (OReilly & Associates) oAppleScript 1-2-3de Sal Soghoian (Peachpit Press).
Prueba y solucin de problemas
Cualquier secuencia de comandos de After Effects que contenga un error que impida que se complete genera
un mensaje de error en la aplicacin. Este mensaje de error contiene informacin sobre la naturaleza del error
y la lnea de la secuencia de comandos en la que se ha producido.
Adems, After Effects incluye un depurador de JavaScript. Para obtener ms informacin sobre cmo activar
y utilizar el depurador, consulte la documentacin del Kit de herramientas de ExtendScript enBridge
JavaScript Reference.
Ms recursos para aprender a utilizar secuencias de comandosExisten muchos recursos para aprender ms sobre las secuencias de comandos que utilizan la norma ECMA.
El motor de secuencias de comandos de After Effects admite la tercera edicin de la norma ECMA-262,
incluidos las convenciones lxicas y de anotacin, tipos, objetos, expresiones e instrucciones.
Para obtener una lista completa de las palabras clave y los operadores que se incluyen con ECMAScript,
consulte el archivo ECMA-262.pdf, disponible en www.ecma-internat ional .org/publicat ions/s tandards/
Ecma-262.htm.
Los libros relativos a JavaScript 1.2 tambin resultan tiles para entender cmo funcionan las secuencias de
comandos en After Effects. Un libro que constituye una norma para los usuarios de JavaScript esJavaScript:
The Definitive Guide (OReilly) de David Flanagan. Otro libro muy til esJavaScript: A Beginners Guide
(Osborne) de John Pollock. Ambos contienen informacin relativa nicamente a las extensiones de JavaScriptpara exploradores de Internet; no obstante, tambin describen de forma detallada los conceptos bsicos de las
secuencias de comandos.
Tambin hay libros sobre cmo usar AppleScript y cmo crear secuencias de comandos desde la lnea de
comandos de Windows, y ambas se pueden utilizar para enviar secuencias a After Effects.
8/6/2019 Gua scripting
10/209
10
Gua de secuencias de comandos de After Effects Escritura de secuencias de comandos
10
Sintaxis de instrucciones y palabras clave
Aunque no se puede proporcionar un recurso que describa de forma exhaustiva el uso de JavaScript, las
siguientes tablas ofrecen una descripcin general de las palabras clave, instrucciones, operadores, prioridad y
asociatividad.
En la siguiente tabla se enumeran y se describen todas las palabras clave e instrucciones que reconoce el motorde secuencias de comandos de After Effects.
Table 1 Sintaxis de instrucciones y palabras clave
Palabra clave/instruccin Descripcin
break JavaScript estndar; cierra el bucle que se est ejecutando actualmente.
con t inue JavaScript estndar; interrumpe la ejecucin de la repeticin del bucle actual.
case Etiqueta que se utiliza en una instruccin switch .
default Etiqueta que se utiliza en una instruccin switch cuando no se encuentra una etiqueta case.
do...while Constructor estndar de JavaScript. Similar al bucle while , salvo que la evaluacin de la condicindel bucle se produce al final del mismo.
false Literal que representa el valor falso booleano.
fo r Construccin de bucle estndar de JavaScript.
for...in Construccin estndar de JavaScript. Proporciona una manera de desplazarse fcilmente por las
propiedades de un objeto.
funct ion Se utiliza para definir una funcin.
if/if...else Construcciones condicionales estndar de JavaScript.
n ew Instruccin de constructor estndar de JavaScript.
nu l l Se asigna a una variable, elemento de conjunto o propiedad de objeto para indicar que no
contiene un valor vlido.
re tu rn Forma estndar de JavaScript de devolver un valor de una funcin o salir de una funcin.
switch Forma estndar de JavaScript de evaluar una expresin de JavaScript e intentar corresponder elvalor de la expresin con una etiqueta case .
th i s Mtodo estndar de JavaScript para indicar el objeto actual.
t r u e Literal que representa el valor verdadero booleano.
undefined Indica que todava no se ha asignado un valor a la variable, elemento de conjunto o propiedad de
objeto.
va r Sintaxis estndar de JavaScript que se utiliza para declarar una variable local.
while Construccin estndar de JavaScript. Similar al bucle do.. .while, salvo que la evaluacin de lacondicin del bucle se produce al principio del mismo.
with Construccin estndar de JavaScript que se utiliza para especificar un objeto que se va a utilizaren instrucciones posteriores.
8/6/2019 Gua scripting
11/209
11
Gua de secuencias de comandos de After Effects Escritura de secuencias de comandos
11
Operadores
En las siguientes tablas se enumeran y se describen todos los operadores que reconoce el motor de secuencia
de comandos de After Effects, y se indica la prior idad y la asociatividad de todos ellos.
Table 2 Descripcin de los operadores
Operadores Descripcin
n ew Asigna un objeto.
delete Anula la asignacin de un objeto.
typeof Devuelve un tipo de datos.
void Devuelve un valor sin definir.
. Miembro de una estructura.
[ ] Elemento de una matriz.
( ) Llamada a una funcin.
+ + Aumento anterior o posterior.
Reduccin anterior o posterior.
Resta o negacin unaria.
~ NOT bit a bit.
! NOT lgico.
* Multiplicar.
/ Dividir.
% Divisin modular.
+ Sumar.
< < Desplazamiento a la izquierda bit a bit.
> > Desplazamiento a la derecha bit a bit.
> > > Desplazamiento a la derecha bit a bit sin signo.
< Menor que.
< = Menor o igual que .
> Mayor que.
> = Mayor o igual que .
= =Igual.
!= Distinto.
& AND bit a bit.
^ XOR bit a bit.
| OR bit a bit.
&& AND lgico.
| | OR lgico.
8/6/2019 Gua scripting
12/209
12
Gua de secuencias de comandos de After Effects Escritura de secuencias de comandos
12
Table 3 Prioridad de los operadores
?: Condicional (ternario).
= Asignacin.
+ = Asignacin con operacin de suma.
= Asignacin con operacin de resta.
*= Asignacin con operacin de multiplicacin.
/ = Asignacin con operacin de divisin.
%= Asignacin con operacin de divisin modular.
< < = Asignacin con operacin de desplazamiento a la izquierda bit a bit.
> > = Asignacin con operacin de desplazamiento a la derecha bit a bit.
> > > = Asignacin con operacin de desplazamiento a la derecha bit a bit sin signo.
&= Asignacin con operacin AND bit a bit.
^ = Asignacin con operacin XOR bit a bit.
| = Asignacin con operacin OR bit a bit.
, Evaluacin mltiple.
Operadores (de mayor a menor prioridad) Asociatividad
[ ] , ( ) , . izquierda a derecha
new, delete, (negacin un aria), ! , typeof, void , ++, derecha a izquierda
*, /, % izquierda a derecha
+, (res ta) izquierda a derecha
, >>> izquierda a derecha
= izquierda a derecha
==, != izquierda a derecha
& izquierda a derecha
^ izquierda a derecha
| izquierda a derecha
&& izquierda a derecha
| | izquierda a derecha
?: derecha a izquierda
=, /= , %=, = , >>>= , &=, ^= , |= , += , = , *= derecha a izquierda
, izquierda a derecha
Operadores Descripcin
8/6/2019 Gua scripting
13/209
13
JavaScript Reference
This chapter lists and describes JavaScript classes, objects, methods, attributes, and global functions defined by
After Effects.
The After Effects scripting engine supports ExtendScript, Adobes extended version of JavaScript, which imple-
ments the 3rd Edition of the ECMA-262 Standard, including its notational and lexical conventions, types,
objects, expressions and statements. For a complete listing of the keywords and operators included with
ECMAScript, refer to ECMA-262.pdf , available at www.ecma-internat ional .org/publicat ions/s tandards/
Ecma-262.htm. For an overview of the most common keywords and statements available from ECMA-262, see
Keywords and statement syntax on page 9.
The After Effects Object Model
As you look through this reference section, which is organized alphabetically by object, you can refer to the
following diagrams for an overview of where the various objects fall within the hierarchy, and their correspon-
dence to the user interface.
Hierarchy diagram of the main After Effects scripting objects
Note that the File and Folder objects are defined by ExtendScript, and are documented in the Bridge JavaScript
Reference. The Socket object is defined by ExtendScript, and is documented in The Socket Object on
page 201.
ExtendScript also defines the ScriptUI module, a set of window and user-interface control objects, which are
available to After Effects scripts. These are documented in the Bridge JavaScript Reference.
8/6/2019 Gua scripting
14/209
14
After Effects Scripting Guide JavaScript Reference
14
The hierarchy of objects in scripting corresponds to the hierarchy in the user interface.
The application contains a Project panel, which displays aproject. The project contains compositions, which
contain layers. The source for a layer can be afootage file,placeholder, or solid, also listed in the Project panel.
Each layer contains settings known asproperties, and these can contain markers and keyframes. The render
queue contains render-queue items as well as render settings and output modules. All of these entities are repre-
sented by objects in scripting.
NOTE: To avoid ambiguity, this manual uses the term attribute to refer to JavaScript object properties, and the
term property or AE property to refer to After-Effects layer properties.
Object summary
The following table lists all objects alphabetically, with links to the documentation page for each.
Object Description
Global functions on page 16 Globally available functions that allow you to display text for script debugging purposes,and help convert time values between seconds and frames.
Application object on page 19 A single global object, available by its name (app ), that provides access to objects andapplication settings within the After Effects application.
AVItem object on page 32 Represents audio/visual files imported into After Effects.
AVLayer object on page 39 Represents those layers that contain AVItems (Comp layers, footage layers, solid layers,
text layers, and sound layers).
CameraLayer object on page 48 Represents a camera layer within a composition.
8/6/2019 Gua scripting
15/209
15
After Effects Scripting Guide JavaScript Reference
15
Collection object on page 49 Associates a set of objects or values as a logical group and provides access to them by
index.
CompItem object on page 50 Represents a composition, and allows you to manipulate it and get information about it.
FileSource object on page 58 Describes footage that comes from a file.
FolderItem object on page 60 Represents a folder in the Project panel.
FootageItem object on page 62 Represents a footage item imported into a project, which appears in the Project panel.
FootageSource object on page 65 Describes the file source of some footage.
ImportOptions object on page 71 Encapsulates options for importing files into After Effects.
Item object on page 74 Represents an item in a project that appears in the Project panel.
ItemCollection object on page 77 Collects items in a project.
KeyframeEase object on page 79 Encapsulates keyframe ease values in an After Effects property.
Layer object on page 81 A base class for layer classes.
LayerCollection object on page 90 Collects layers in a project.
LightLayer object on page 94 Represents a light layer within a composition.
MarkerValue object on page 95 Encapsulates marker values in an AE property.
MaskPropertyGroup object on page 97 Encapsulates mask attributes in a layer.
OMCollection object on page 99 Collects output modules in a render queue.
OutputModule object on page 100 Represents an output module for a render queue.
PlaceholderSource object on page 103 Describes a placeholder for footage.
Project object on page 104 Represents an After Effects project.
Property object on page 113 Represents an After Effects property.
PropertyBase object on page 135 A base class for After Effects property and property group classes.
PropertyGroup object on page 142 Represents an After Effects property group.
RenderQueue object on page 147 Represents the After Effects render queue.
RenderQueueItem object on page 150 Represents a renderable item in a render queue.
RenderQueueItem object on page 150 Collects render-queue items in a render queue.
RQItemCollection object on page 156 Provides access to application settings and preferences.
Shape object on page 159 Encapsulates the outline shape information for a mask.
SolidSource object on page 162 Describes a solid color that is the source of some footage.
System object on page 163 Provides access to the operating system from the application.
TextDocument object on page 165 Encapsulates the text in a text layer.
TextLayer object on page 166 Represents a text layer within a composition.
Object Description
8/6/2019 Gua scripting
16/209
16
After Effects Scripting Guide JavaScript Reference
16
Global functions
These globally available functions that are specific to After Effects. Any JavaScript object or function can call
these functions, which allow you to display text in a small (3-line) area of the Info panel, and to convert
numeric time values to and from string values.
Additional global functions for standard user I/O (a lert , confirm , and prompt) and static functions for fileI/O, are defined by ExtendScript; for detailed reference information, see the Bridge JavaScript Reference.
NOTE: The After Effects global functions for standard dialogs and file I/O are still supported in this release, but
are deprecated and will not be supported in future releases. For details, see the After Effects 6.5 documentation.
clearOutput() global function
clearOutput()
Description
Clears the output in the Info panel.
Parameters
None.
Returns
Nothing.
currentFormatToTime() global function
currentFormatToTime( formattedTime, fps, i sDuration)
Description
Converts a formatted string for a frame time value to a number of seconds, given a specified frame rate. For
example, if the formatted frame time value is 0:00:12 (the exact string format is determined by a project
setting), and the frame rate is 24 fps, the time would be 0.5 seconds (12/24). If the frame rate is 30 fps, the timewould be 0.4 seconds (12/30).
If the time is a duration, the frames are counted from 0. Otherwise, the frames are counted from the projects
starting frame (see Project displayStartFrame attribute on page 106).
Parameters
Global function Description
write() Writes text to the Info panel, with no line break added.
writeLn() Writes text to the Info panel, adding a line break at the end.
clearOutput() Clears text from the Info panel.
timeToCurrentFormat() Converts a numeric time value to a string time value.
currentFormatToTime() Converts string time value to a numeric time value.
formattedTime The frame time value, a string specifying a number of frames in the projects current time display format.
fps The frames-per-second, a floating-point value.
8/6/2019 Gua scripting
17/209
17
After Effects Scripting Guide JavaScript Reference
17
Returns
Floating-point value, the number of seconds.
timeToCurrentFormat() global function
timeToCurrentFormat( t ime, fps , i sDuration)
Description
Converts a numeric time value (a number of seconds) to a frame time value; that is, a formatted string that
shows which frame corresponds to that time, at the specified rate. For example, if the time is 0.5 seconds, and
the frame rate is 24 fps, the frame would be 0:00:12 (when the project is set to Display Timecode). If the frame
rate is 30 fps, the frame would be 0:00:15. The format of the timecode string is determined by a project setting.
If the time is a duration, the frames are counted from 0. Otherwise, the frames are counted from the projects
starting frame (see Project displayStartFrame attribute on page 106).
Parameters
Returns
String in the projects current time display format.
write() global function
write( text )
Description
Writes output to the Info panel, with no line break added.
Parameters
Returns
Nothing.
Example
write("This text appears in Info panel ") ;
write("with more on same l ine . ") ;
isDurat ion Optional. When true, the time is a duration (measured from frame 0). When false (the default), the time ismeasured from the projects starting frame.
t ime The number of seconds, a floating-point value.
fps The frames-per-second, a floating-point value.
i sDurat ion Optional. When true, the time is a duration (measured from frame 0). When false (the default), the time ismeasured from the projects starting frame.
text The string to display. Truncated if too long for the Info panel.
8/6/2019 Gua scripting
18/209
18
After Effects Scripting Guide JavaScript Reference
18
writeLn() global function
writeLn( text )
Description
Writes output to the Info panel and adds a line break at the end.
Parameters
Returns
Nothing.
Example
write ln("This text appears on f irs t l ine") ;
write ln("This text appears on second l ine") ;
text The string to display.
8/6/2019 Gua scripting
19/209
19
After Effects Scripting Guide JavaScript Reference
19
Application object
app
Description
Provides access to objects and application settings within the After Effects application. The single global objectis always available by its name, app .
Attributes of the Application object provide access to specific objects within After Effects. Methods of the
Application object can create a project, open an existing project, control Watch Folder mode, purge memory,
and quit the After Effects application. When the After Effects application quits, it closes the open project,
prompting the user to save or discard changes as necessary, and creates a project file as necessary.
Attributes
Attribute Reference Description
project Application project attribute onpage 27 and Project object on
page 104
The current After Effects project.
language Application language attribute onpage 25
The language in which the application is running.
vers ion Application version attribute onpage 30
The version number of the After Effects application.
seria lNumber Application serialNumber attribute onpage 29
The serial number of the After Effects installation.
regis teredName Application registeredName attributeon page 28
The user name to which the After Effects installation is
registered.
regis teredCompany Application registeredCompanyattribute on page 28
The company to which the After Effects installation is
registered.
buildName Application buildName attribute onpage 21
The name of this build of the application.
buildNumber Application buildNumber attribute onpage 22
The number of this build of the application.
isProfessionalVersion Application isProfessionalVersionattribute on page 24
When true, the installation is the Professional Edition.
isWatchFolder Application isWatchFolder attributeon page 25
When true, the local application is running in Watch
Folder mode.
i sRenderEngine Application isRenderEngine attributeon page 24
When true, the local After Effects application is installed
as a render engine.
se t t ings Application settings attribute onpage 30 and RQItemCollection object
on page 156
Application settings that can be set via scripting.
onError Application onError attribute onpage 26
A callback function that is called when an error occurs
in the application.
exitCode Application exitCode attribute onpage 24
A numeric status code used when executing a script
externally (that is, from a command line or AppleScript).
0 if no error occurred. A positive number indicates an
error that occurred while running the script.
exitAfterLaunchAndEval Application exitAfterLaunchAndEvalattribute on page 23
When true, the application remains open after running
a script from the command line on Windows.
8/6/2019 Gua scripting
20/209
20
After Effects Scripting Guide JavaScript Reference
20
Methods
Application activate() method
app.act ivate()
Description
Opens the application main window if it is minimized or iconified, and brings it to the front of the desktop.
Parameters
None.
saveProjectOnCrash Application saveProjectOnCrashattribute on page 28
When true, the project is saved if the application closes
unexpectedly.
Method Reference Description
newProject() Application newProject() method onpage 25
Creates a new project in After Effects.
open() Application open() method on page 26 Opens a project or an Open Project dialog box.
quit() Application quit() method on page 28 Quits the application.
watchFolder() Application watchFolder() method onpage 30
Starts Watch Folder mode; does not return
until Watch Folder mode is turned off.
pauseWatchFolder() Application pauseWatchFolder() methodon page 27
Pauses a current watch-folder process.
endWatchFolder() Application endWatchFolder() method onpage 23
Ends a current watch-folder process.
purge() Application purge() method on page 27 Purges a targeted type of cached information(replicates Purge options in the Edit menu).
beginUndoGroup() Application beginUndoGroup() methodon page 21
Groups the actions that follow it into a single
undoable step.
endUndoGroup() Application endUndoGroup() method onpage 22
Ends an undo group; needed only when a
script contains more than one undo group.
beginSuppressDia logs() Application beginSuppressDialogs()method on page 21
Begins suppression of dialogs in the user inter-
face.
endSuppressDia logs() Application endSuppressDialogs()
method on page 22
Ends suppression of dialogs in the user inter-
face.
se tMemoryUsageLimits() Application setMemoryUsageLimits()method on page 29
Sets memory usage limits as in the Memory &
Cache preferences area.
se tSavePreferencesOnQuit() Application setSavePreferencesOnQuit()method on page 30
Sets whether preferences are saved when the
application is quit.
act ivate() Application activate() method on page 20 Brings the After Effects main window to thefront of the screen.
scheduleTask() Application scheduleTask() method onpage 29
Schedules a JavaScript script for delayed exe-
cution.
cancelTask() Application cancelTask() method onpage 22
Cancels a scheduled task.
Attribute Reference Description
8/6/2019 Gua scripting
21/209
21
After Effects Scripting Guide JavaScript Reference
21
Returns
Nothing.
Application beginSuppressDialogs() method
app.beginSuppressDia logs()
Description
Begins suppression of script error dialog boxes in the user interface. Use endSuppressDia logs() to resume the
display of error dialogs. See Application endSuppressDialogs() method on page 22.
Parameters
None.
Returns
Nothing.
Application beginUndoGroup() method
app.beginUndoGroup(undoStr ing)
Description
Marks the beginning of an undo group, which allows a script to logically group all of its actions as a single
undoable action (for use with the Edit > Undo/Redo menu items). Use the endUndoGroup() method to mark
the end of the group. (See Application endUndoGroup() method on page 22.)
beginUndoGroup() and endUndoGroup() pairs can be nested. Groups within groups become part of the
larger group, and will undo correctly. In this case, the names of inner groups are ignored.
Parameters
Returns
Nothing.
Application buildName attribute
app.bui ldName
Description
The name of the build of After Effects being run, used internally by Adobe for testing and troubleshooting.
Type
String; read-only.
undoString The text that will appear for the Undo command in the Edit menu (that is, Undo )
8/6/2019 Gua scripting
22/209
22
After Effects Scripting Guide JavaScript Reference
22
Application buildNumber attribute
app.bui ldNumber
Description
The number of the build of After Effects being run, used internally by Adobe for testing and troubleshooting.
Type
Integer; read-only.
Application cancelTask() method
app.cancelTask( taskID)
Description
Removes the specified task from the queue of tasks scheduled for delayed execution.
Parameters
Returns
Nothing.
Application endSuppressDialogs() method
app.endSuppressDia logs(aler t )
Description
Ends the suppression of script error dialog boxes in the user interface. Error dialogs are displayed by default;
call this method only ifbeginSuppressDia logs() has previously been called. See Application beginSuppress-
Dialogs() method on page 21.
Parameters
Returns
Nothing.
Application endUndoGroup() method
app.endUndoGroup()
Description
Marks the end of an undo group begun with the app.beginUndoGroup() method. You can use this method
to place an end to an undo group in the middle of a script, should you wish to use more than one undo group
for a single script.
If you are using only a single undo group for a given script, you do not need to use this method; in its absence
at the end of a script, the system will close the undo group automatically.
taskID An integer that identifies the task, as returned by app.scheduleTask() .
a lert Boolean; when true, errors that have occurred following the call to beginSuppressDia logs() are displayed in adialog box.
8/6/2019 Gua scripting
23/209
23
After Effects Scripting Guide JavaScript Reference
23
Calling this method without having set a beginUndoGroup() method yields an error.
Parameters
None.
Returns
Nothing.
Application endWatchFolder() method
app.endWatchFolder()
Description
Ends Watch Folder mode.
Parameters
None
Returns
Nothing.
See also
Application watchFolder() method on page 30Application pauseWatchFolder() method on page 27Application isWatchFolder attribute on page 25
Application exitAfterLaunchAndEval attribute
app.ex itAfterLaunchAndEval
Description
This attribute is used only when executing a script from a command line on Windows. When the application
is launched from the command line, the r or s command line flag causes the application to run a script
(from a file or from a string, respectively).
If this attribute is set to true, After Effects will exit after the script is run; if it is false, the application will remain
open.
This attribute only has an effect when After Effects is run from the Windows command line. It has no effect
in Mac OS.
Type
Boolean; read/write.
8/6/2019 Gua scripting
24/209
24
After Effects Scripting Guide JavaScript Reference
24
Application exitCode attribute
app.ex itCode
Description
A numeric status code used when executing a script externally (that is, from a command line or AppleScript). In Windows, the value is returned on the command line when After Effects was launched on the commands
line (using the afterfx or aftgerfx m command), and a script was specified with the r or s option.
in Mac OS, the value is returned as the Applescript DoScript result for each script.
In both Mac OS and Windows, the value is set to 0 (EXIT_SUCCESS) at the beginning of each script evalu-
ation. In the event of an error while the script is running, the script can set this to a positive integer that
indicates what error occured.
Type
Integer; read/write.
Example
app.ex itCode = 2; / /on quit , i f va lue is 2 , an error has occurred
Application isProfessionalVersion attribute
app.isProfessionalVersion
Description
True if the locally installed After Effects application is the Professional Edition, false if it is the Standard
Edition.
TypeBoolean; read-only.
Example
var PB = app. isProfess ionalVers ion;
a lert("I t i s " + PB + " that you are running the Profess ional Edit ion.") ;
Application isRenderEngine attribute
app. isRenderEngine
Description
True if an installation of After Effects is a Render Engine-only installation.
Type
Boolean; read-only.
8/6/2019 Gua scripting
25/209
25
After Effects Scripting Guide JavaScript Reference
25
Application isWatchFolder attribute
app.isWatchFolder
Description
True if the Watch Folder dialog box is currently displayed and the application is currently watching a folderfor rendering.
Type
Boolean; read-only.
Application language attribute
app. language
Description
The language After Effects is running.
Type
A Language enumerated value; read-only. One of:
Language .ENGLISH
Language .FRENCH
Language .GERMAN
Language . ITALIAN
Language . JAPANESE
Language .SPANISH
Example
var lang = app. language ;
i f ( lang == Language .ENGLISH)
alert("After Ef fects is running in English . ") ;
e lse i f ( lang == Language .FRENCH)
alert("After Ef fects is running in French.") ;
e lse
a lert("After Ef fects is not running in English or French.") ;
Application newProject() method
app.newProject()
Description
Creates a new project in After Effects, replicating the File > New > New Project menu command.
If the current project has been edited, the user is prompted to save it. If the user cancels out of the Save dialog
box, the new project is not created and the method returns null. Use app.project .close(CloseOp-
t ions .DO_NOT_SAVE_CHANGES) to close the current project before opening a new one. See Project
close() method on page 105.
Parameters
None.
8/6/2019 Gua scripting
26/209
26
After Effects Scripting Guide JavaScript Reference
26
Returns
A new Project object, or null if no new project is created.
Example
app.project .close(CloseOptions .DO_NOT_SAVE_CHANGES) ;
app.newProject() ;
Application onError attribute
app.onError
Description
The name of a callback function that is called when an error occurs. By creating a function and assigning it to
this attribute, you can respond to errors systematically; for example, you can close and restart the application,
noting the error in a log file if it occurred during rendering. See RenderQueue render() method on page 148.
The callback function is passed the error string and a severity string. It should not return any value.
Type
A function name string, or null if no function is assigned; read/write.
Example
funct ion err(errString) {
a lert(errString) ;
}
app.onError = err ;
Application open() method
app.open()
app.open( fi le)
Description
Opens a project.
Parameters
Returns
A new Project object for the specified project, or null if the user cancels the Open dialog box.
Example
var my_fi le = new Fi le(" . . /my_folder/my_test .aep") ;
i f (my_fi le .ex is ts){
new_project = app.open(my_fi le) ;
i f (new_project){
a lert(new_project . f i le .name) ;
}
f i le Optional. An ExtendScript File object for the project file to open. If not supplied, the method prompts theuser to select a project file.
8/6/2019 Gua scripting
27/209
27
After Effects Scripting Guide JavaScript Reference
27
}
Application pauseWatchFolder() method
app.pauseWatchFolder(pause)
Description
Pauses or resumes the search of the target watch folder for items to render.
Parameters
Returns
Nothing.
See also
Application isWatchFolder attribute on page 25Application watchFolder() method on page 30Application endWatchFolder() method on page 23
Application project attribute
app.project
Description
The project that is currently loaded. See Project object on page 104.
Type
Project object; read-only.
Application purge() method
app.purge(targe t )
Description
Purges unused data of the specified types from memory. Replicates the Purge options in the Edit menu.
Parameters
Returns
Nothing.
pause True to pause, false to resume.
target The type of elements to purge from memory; a PurgeTarget enumerated value, one of:
PurgeTarget.ALL_CACHES : Purges all data that After Effects has cached to physical memory.
PurgeTarget .UNDO_CACHES: Purges all data saved in the undo cache.
PurgeTarget.SNAPSHOT_CACHES : Purges all data cached as comp/layer snapshots.
PurgeTarget.IMAGE_CACHES : Purges all saved image data.
8/6/2019 Gua scripting
28/209
28
After Effects Scripting Guide JavaScript Reference
28
Application quit() method
app.quit()
Description
Quits the After Effects application.
Parameters
None.
Returns
Nothing.
Application registeredCompany attribute
app.regis teredCompany
Description
The name (if any) that the user of the application entered as the registered company at the time of installation.
Type
String; read-only.
Example
var company = app.regis teredCompany;
alert(Your company name is + company + .);
Application registeredName attribute
app.regis teredName
Description
The user name, if any, that the user of the application entered for the registered name at the time of instal-
lation.
Type
String; read-only.
Example
var userName = app.regis teredName;
confirm(Are you + userName + ?) ;
Application saveProjectOnCrash attribute
app.saveProjectOnCrash
Description
When true (the default), After Effects attempts to display a dialog box that allows you to save the current
project if an error causes the application to quit unexpectedly. Set to false to suppress this dialog box and quit
without saving.
8/6/2019 Gua scripting
29/209
29
After Effects Scripting Guide JavaScript Reference
29
Type
Boolean; read/write.
Application scheduleTask() method
app.scheduleTask( stringToExecute, delay, repeat)
Description
Schedules the specified JavaScript for delayed execution.
Parameters
Returns
Integer, a unique identifier for this task, which can be used to cancel it with app.cancelTask() .
Application serialNumber attribute
app.seria lNumber
Description
The alphanumeric string that is the serial number of the installed version of After Effects.
Type
String; read-only.
Example
var seria l = app.seria lNumber;
a lert("This copy is seria l number " + seria l) ;
Application setMemoryUsageLimits() method
app.setMemoryUsageLimits(imageCachePercentage , maximumMemoryPercentage)
Description
Sets memory usage limits as in the Memory & Cache preferences area. For both values, if installed RAM is lessthan a given amount (n gigabytes), the value is a percentage of the installed RAM, and is otherwise a
percentage ofn. The value ofn is: 2 Gb for Win32, 4 Gb for Win64, 3.5 Gb for Mac OS.
Parameters
stringToExecute A string containing JavaScript to be executed.
delay A number of milli seconds to wait before executing the JavaScript. A floating-point value.
repeat When true, execute the script repeatedly, with the specified delay between each execution. When falsethe script is executed only once.
imageCachePercentage Floating-point value, the percentage of memory assigned to image cache.
maximumMemoryPercentage Floating-point value, the maximum usable percentage of memory.
8/6/2019 Gua scripting
30/209
30
After Effects Scripting Guide JavaScript Reference
30
Returns
Nothing.
Application setSavePreferencesOnQuit() method
app.setSavePreferencesOnQuit(doSave )
Description
Set or clears the flag that determines whether preferences are saved when the application is closed.
Parameters
Returns
Nothing.
Application settings attribute
app.set t ings
Description
The currently loaded settings. See RQItemCollection object on page 156.
Type
Settings object; read-only.
Application version attribute
app.vers ion
Description
An alphanumeric string indicating which version of After Effects is running.
Type
String; read-only.
Example
var ver = app.vers ion;
a lert("This machine is running vers ion " + ver + " o f After Ef fects . ") ;
Application watchFolder() method
app.watchFolder( fo lder_object_to_watch)
Description
Starts a Watch Folder (network rendering) process pointed at a specified folder.
doSave When true, preferences saved on quit, when false they are not.
8/6/2019 Gua scripting
31/209
31
After Effects Scripting Guide JavaScript Reference
31
Parameters
Returns
Nothing.
Example
var theFolder = new Folder(c: / tool) ;
app.watchFolder( theFolder) ;
See also
Application endWatchFolder() method on page 23Application pauseWatchFolder() method on page 27Application isWatchFolder attribute on page 25
fo lder_object_to_watch The ExtendScript Folder object for the folder to watch.
8/6/2019 Gua scripting
32/209
32
After Effects Scripting Guide JavaScript Reference
32
AVItem object
app.project . i tem(index)
Description
The AVitem object provides access to attributes and methods of audio/visual files imported into After Effects.
AVItem is a subclass of Item. All methods and attributes of Item, in addition to those listed below, are
available when working with AVItem. See Item object on page 74.
AVItem is the base class for both CompItem and FootageItem, so AVItem attributes and methods are also
available when working with CompItem and FootageItem objects. See CompItem object on page 50 and
FootageItem object on page 62.
Attributes
Methods
Attribute Reference Description
name AVItem name attribute on page 35 The name of the object as shown in the Project panel.
widt h AVItem width attribute on page 38 The width of the item.
height AVItem height attribute on page 34 The height of the item.
pixe lAspect AVItem pixelAspect attribute on page 35 The pixel aspect ratio of the item.
frameRate AVItem frameRate attribute on page 34 The frame rate of the item.
frameDurat ion AVItem frameDuration attribute on page 33 The frame duration for the item.
durat ion AVItem duration attribute on page 33 The total duration of the item.
useProxy AVItem useProxy attribute on page 38 When true, a proxy source is used for this item.
proxySource AVItem proxySource attribute on page 35 The FootageItem object used as proxy for the item.
t ime AVItem time attribute on page 38 Current time of the item.
usedIn AVItem usedIn attribute on page 38 The CompItem objects that use this item.
hasVideo AVItem hasVideo attribute on page 34 When true, the item has a video component.
hasAudio AVItem hasAudio attribute on page 34 When true, the item has an audio component.
footageMiss ing AVItem footageMissing attribute onpage 33
When true, the item cannot be found or is a placeholder.
Method Reference Description
setProxy() AVItem setProxy() method on page 36 Sets a proxy for the item.
se tProxyWithSequence() AVItem setProxyWithSequence() method onpage 37
Sets a sequence as a proxy for theitem.
se tProxyWithSolid() AVItem setProxyWithSolid() method onpage 37
Sets a solid as a proxy for the item.
se tProxyWithPlaceholder() AVItem setProxyWithPlaceholder() method onpage 36
Sets a placeholder as a proxy for the item.
setProxyToNone() AVItem setProxyToNone() method on page 36 Removes the proxy for the item.
8/6/2019 Gua scripting
33/209
33
After Effects Scripting Guide JavaScript Reference
33
AVItem duration attribute
app.project . i tem( index) .durat ion
Description
Returns the duration, in seconds, of the item. Still footage items have a duration of 0. In a CompItem, the value is linked to the durat ion of the composition, and is read/write.
In a FootageItem, the value is linked to the durat ion of the mainSource object, and is read-only.
Type
Floating-point value in the range [0.0..10800.0]; read/write for a CompItem; otherwise, read-only.
AVItem footageMissing attribute
app.project . i tem( index) .footageMiss ing
Description
When true, the AVItem is a placeholder, or represents footage with a source file that cannot be found. In this
case, the path of the missing source file is in the miss ingFootagePath attribute of the footage items source-file
object. See FootageItem mainSource attribute on page 63 and FileSource missingFootagePath attribute on
page 58.
Type
Boolean; read-only.
AVItem frameDuration attribute
app.project . i tem( index) .frameDurat ion
Description
Returns the length of a frame for this AVItem, in seconds. This is the reciprocal of frameRate. When set, the
reciprocal is automatically set as a new frameRate value.
This attribute returns the reciprocal of the frameRate , which may not be identical to a value you set, if that
value is not evenly divisible into 1.0 (for example, 0.3). Due to numerical limitations, (1 / ( 1 / 0.3) ) is close
to, but not exactly, 0.3.
If the AVItem is a FootageItem, this value is linked to the mainSource , and is read-only. To change it, set the
conformFrameRate of the mainSource object. This sets both the frameRate and frameDurat ion of the
FootageItem.
Type
Floating-point value in the range [1/99 .. 1.0 ]; read-only for a FootageItem, otherwise read/write.
8/6/2019 Gua scripting
34/209
34
After Effects Scripting Guide JavaScript Reference
34
AVItem frameRate attribute
app.project . i tem( index) .frameRate
Description
The frame rate of the AVItem, in frames-per-second. This is the reciprocal of the frameDurat ion . When set,the reciprocal is automatically set as a new frameDurat ion value.
In a CompItem, the value is linked to the frameRate of the composition, and is read/write.
In a FootageItem, the value is linked to the frameRate of the mainSource object, and is read-only. To change
it, set the conformFrameRate of the mainSource object. This sets both the frameRate and frameDurat ion
of the FootageItem.
Type
Floating-point value in the range [1.0..99.0]; read-only for a FootageItem, otherwise read/write.
AVItem hasAudio attribute
app.project . i tem( index) .hasAudio
Description
When true , the AVItem has an audio component.
In a CompItem, the value is linked to the composition.
In a FootageItem, the value is linked to the mainSource object.
Type
Boolean; read-only.
AVItem hasVideo attribute
app.project . i tem( index) .hasVideo
Description
When true , the AVItem has an video component.
In a CompItem, the value is linked to the composition.
In a FootageItem, the value is linked to the mainSource object.
Type
Boolean; read-only.
AVItem height attribute
app.project . i tem( index) .height
Description
The height of the item in pixels.
In a CompItem, the value is linked to the composition, and is read/write.
8/6/2019 Gua scripting
35/209
35
After Effects Scripting Guide JavaScript Reference
35
In a FootageItem, the value is linked to the mainSource object, and is read/write only if the mainSource
object is a SolidSource. Otherwise, it is read-only.
Type
Integer in the range [1...30000]; read/write, except as noted.
AVItem name attribute
app.project . i tem( index) .name
Description
The name of the item, as shown in the Project panel.
In a FootageItem, the value is linked to the mainSource object. If the mainSource object is a FileSource, this
value controls the display name in the Project panel, but does not affect the file name.
Type
String; read/write.
AVItem pixelAspect attribute
app.project . i tem( index) .pixe lAspect
Description
The pixel aspect ratio of the item.
In a CompItem, the value is linked to the composition.
In a FootageItem, the value is linked to the mainSource object.
Certain pixe lAspect values are specially known to After Effects, and are stored and retrieved with perfect
accuracy. These are the set { 1, 0 .9, 1 .2, 1 .07, 1.42, 2, 0 .95, 1.9 } . Other values may show slight rounding
errors when you set or get them; that is, the value you retrieve after setting may be slightly different from the
value you supplied.
Type
Floating-point value, in the range [0.01..100.0]; read/write.
AVItem proxySource attribute
app.project . i tem( index) .proxySource
Description
The FootageSource being used as a proxy. The attribute is read-only; to change it, call any of the AVItem
methods that change the proxy source: setProxy() , se tProxyWithSequence(), se tProxyWithSolid(), or
se tProxyWithPlaceholder().
Type
FootageSource object; read-only.
8/6/2019 Gua scripting
36/209
36
After Effects Scripting Guide JavaScript Reference
36
AVItem setProxy() method
app.project . i tem( index).setProxy( fi le)
Description
Sets a file as the proxy of this AVItem. Loads the specified file into a new FileSource object, sets this as the valueof the proxySource attribute, and sets useProxyto true. It does not preserve the interpretation parameters,
instead using the user preferences. If the file has an unlabeled alpha channel, and the user preference says to
ask the user what to do, the method estimates the alpha interpretation, rather than asking the user.
This differs from setting a FootageItem's main source, but both actions are performed as in the user interface.
Parameters
Returns
None.
AVItem setProxyToNone() method
app.project . i tem( index).setProxyToNone()
Description
Removes the proxy from this AVItem, sets the value ofproxySource to null, and sets the value ofuseProxyto
fa lse .
Parameters
None.
Returns
Nothing.
AVItem setProxyWithPlaceholder() method
app.project . i tem( index). se tProxyWithPlaceholder(name, width, he ight , frameRate , duration)
Description
Creates a PlaceholderSource object with specified values, sets this as the value of the proxySource attribute,
and sets useProxyto true. It does not preserve the interpretation parameters, instead using the user prefer-
ences.
NOTE: There is no direct way to set a placeholder as a proxy in the user interface; this behavior occurs when a proxy
has been set and then moved or deleted.
Parameters
f i le An ExtendScript File object for the file to be used as a proxy.
name A string containing the name of the new object.
width, he ight The pixel dimensions of the placeholder, an integer in the range [4..30000].
frameRate The frames-per-second, an integer in the range [1..99].
8/6/2019 Gua scripting
37/209
37
After Effects Scripting Guide JavaScript Reference
37
Returns
Nothing.
AVItem setProxyWithSequence() method
app.project . i tem( index). se tProxyWithSequence( fi le , forceAlphabetical)
Description
Sets a sequence of files as the proxy of this AVItem, with the option of forcing alphabetical order. Loads the
specified file sequence into a new FileSource object, sets this as the value of the proxySource attribute, and sets
useProxyto true. It does not preserve the interpretation parameters, instead using the user preferences. If any
file has an unlabeled alpha channel, and the user preference says to ask the user what to do, the method
estimates the alpha interpretation, rather than asking the user.
Parameters
Returns
Nothing.
AVItem setProxyWithSolid() method
app.project . i tem( index). se tProxyWithSolid(co lor , name, width, he ight , p ixe lAspect )
Description
Creates a SolidSource object with specified values, sets this as the value of the proxySource attribute, and sets
useProxyto true. It does not preserve the interpretation parameters, instead using the user preferences.
NOTE: There is no way, using the user interface, to set a solid as a proxy; this feature is available only through
scripting.
Parameters
Returns
Nothing.
durat ion The total length in seconds, up to 3 hours. An integer in the range [0.0..10800.0].
f i le An ExtendScript File object for the first file in the sequence.
forceAlphabet ica l When true, use the Force alphabetical order option.
color The color of the solid, an array of 3 floating-point values, [R, G, B], in the range [0.0..1.0].
name A string containing the name of the new object.
width, he ight The pixel dimensions of the placeholder, an integer in the range [1...30000].
pixe lAspect The pixel aspect of the solid, a floating-point value in the range [0.01... 100.0].
8/6/2019 Gua scripting
38/209
38
After Effects Scripting Guide JavaScript Reference
38
AVItem time attribute
app.project . i tem( index) .t ime
Description
The current time of the item when it is being previewed directly from the Project panel. This value is a numberof seconds. Use the global method timeToCurrentFormat to convert it to a string value that expresses the time
in terms of frames; see timeToCurrentFormat() global function on page 17.
It is an error to set this value for a FootageItem whose mainSource is still (i tem.mainSource . isSt i l l is true).
Type
Floating-point value; read/write.
AVItem usedIn attribute
app.project . i tem( index) .usedIn
Description
All the compositions that use this AVItem.
Note: Upon retrieval, the array value is copied, so it is not automatically updated. If you get this value, then add
this item into another composition, you must retrieve the value again to get an array that includes the new item.
Type
Array of CompItem objects; read-only.
AVItem useProxy attribute
app.project . i tem( index) .useProxy
Description
When true, a proxy is used for the item. It is set to true by all the SetProxymethods, and to false by the
SetProxyToNone() method.
Type
Boolean; read/write.
AVItem width attribute
app.project . i tem( index) .widt h
Description
The width of the item, in pixels.
In a CompItem, the value is linked to the composition, and is read/write.
In a FootageItem, the value is linked to the mainSource object, and is read/write only if the mainSource
object is a SolidSource. Otherwise, it is read-only.
Type
Integer in the range [1...30000]; read/write, except as noted.
8/6/2019 Gua scripting
39/209
39
After Effects Scripting Guide JavaScript Reference
39
AVLayer object
app.project. layer(index)
Description
The AVLayer object provides an interface to those layers that contain AVItems (Comp layers, footage layers,solid layers, text layers, and sound layers).
AVLayer is a subclass of Layer. All methods and attributes of Layer, in addition to those listed below, are
available when working with AVLayer. See Layer object on page 81.
AVLayer is a base class for TextLayer, so AVLayer attributes and methods are available when working with
TextLayer objects. See TextLayer object on page 166.
AE Properties
Different types of layers have different AE properties. AVLayer has the following properties and property
groups:
Marker
Time Remap
Motion Trackers
Masks
Effects
Transform
Anchor Point
Pos it ion
Sca le
Orientat ion
X Rotat ion
Y Rotat ion
Rotat ionOpacity
Materia l Options
Casts Shadows
Light Transmiss ion
Accepts Shadows
Accepts Lights
Ambient
Dif fuse
Specular
Shininess
Meta l
AudioAudio Leve ls
Example
If the first item in the project is a CompItem, and the first layer of that CompItem is an AVLayer, the following
sets the layer quali ty , s tartTime , and inPoint.
var f irs tLayer = app.project . i tem(1) . layer(1) ;
f irs tLayer.quali ty = LayerQuali ty .BEST;
f irs tLayer.s tartTime = 1;
f irs tLayer. inPoint = 2;
8/6/2019 Gua scripting
40/209
40
After Effects Scripting Guide JavaScript Reference
40
Attributes
Attribute Reference Description
source AVLayer source attribute on page 46 The source item for this layer.
i sNameFromSource AVLayer isNameFromSource attributeon page 45 When true, the layer has no expressly set name,but contains a named source.
height AVLayer height attribute on page 44 The height of the layer.
widt h AVLayer width attribute on page 47 The width of the layer.
audioEnabled AVLayer audioEnabled attribute onpage 42
When true, the layer's audio is enabled.
motionBlur AVLayer motionBlur attribute onpage 45
When true, the layer's motion blur is enabled.
ef fectsAct ive AVLayer effectsActive attribute onpage 43
When true, the layer's effects are active.
adjustmentLayer AVLayer adjustmentLayer attribute on
page 41
When true, this is an adjustment layer.
guideLayer AVLayer guideLayer attribute onpage 44
When true, this is a guide layer.
threeDLayer AVLayer threeDLayer attribute onpage 46
When true, this is a 3D layer.
canSetCollapseTransformation AVLayer canSetCollapseTransformationattribute on page 43
When true, it is legal to change the value of
col lapseTransformation.
col lapseTransformation AVLayer collapseTransformationattribute on page 43
When true, collapse transformation is on.
frameBlending AVLayer frameBlending attribute onpage 44
When true, frame blending is enabled.
canSetTimeRemapEnabled AVLayer canSetTimeRemapEnabledattribute on page 43
When true, it is legal to change the value of
t imeRemapEnabled.
t imeRemapEnabled AVLayer timeRemapEnabled attributeon page 46
When true, time remapping is enabled on this
layer.
hasAudio AVLayer hasAudio attribute onpage 44
When true, the layer contains an audio compo-
nent.
audioAct ive AVLayer audioActive attribute onpage 41
When true, the layer's audio is active at the cur-
rent time.
blendingMode AVLayer blendingMode attribute onpage 42
The blending mode of the layer.
preserveTransparency AVLayer preserveTransparency
attribute on page 45
When true, preserve transparency is enabled.
trackMatteType AVLayer trackMatteType attribute onpage 46
if layer has a track matte, specifies the way it is
applied.
isTrackMatte AVLayer isTrackMatte attribute onpage 45
When true, this layer is being used as a track
matte for the layer below it.
hasTrackMatte AVLayer hasTrackMatte attribute onpage 44
When true, the layer above is being used as a
track matte on this layer.
quali ty AVLayer quality attribute on page 45 The layer quality setting.
8/6/2019 Gua scripting
41/209
41
After Effects Scripting Guide JavaScript Reference
41
Method
AVLayer adjustmentLayer attribute
app.project . i tem( index) .adjustmentLayer
Description
True if the layer is an adjustment layer.
Type
Boolean; read/write.
AVLayer audioActive attributeapp.project . i tem( index) .audioAct ive
Description
True if the layer's audio is active at the current time.
For this value to be true, audioEnabled must be true, no other layer with audio may be soloing unless this layer
is soloed too, and the time must be between the inPoint and outPoint of this layer.
Type
Boolean; read-only.
AVLayer audioActiveAtTime() method
app.project . i tem( index). audioAct iveAtTime(t ime)
Description
Returns true if this layer's audio will be active at the specified time.
For this method to return true, audioEnabled must be true, no other layer with audio may be soloing unless
this layer is soloed too, and the time must be between the inPoint and outPoint of this layer.
Parameters
Returns
Boolean.
Method Reference Description
audioAct iveAtTime() AVLayer audioActiveAtTime() methodon page 41
Reports whether this layer's audio is active at a given time.
t ime The time, in seconds. A floating-point value.
8/6/2019 Gua scripting
42/209
42
After Effects Scripting Guide JavaScript Reference
42
AVLayer audioEnabled attribute
app.project . i tem( index) .audioEnabled
Description
When true, the layer's audio is enabled. This value corresponds to the audo toggle switch in the Timelinepanel.
Type
Boolean; read/write.
AVLayer blendingMode attribute
app.project . i tem( index) .blendingMode.
Description
The blending mode of the layer.
Type
A BlendingMode enumerated value; read/write. One of:
BlendingMode.ADD
BlendingMode.ALPHA_ADD
BlendingMode.CLASSIC_COLOR_BURN
BlendingMode.CLASSIC_COLOR_DODGE
BlendingMode.CLASSIC_DIFFERENCE
BlendingMode.COLOR
BlendingMode.COLOR_BURN
BlendingMode.COLOR_DODGE
BlendingMode.DANCING_DISSOLVEBlendingMode.DARKEN
BlendingMode.DIFFERENCE
BlendingMode.DISSOLVE
BlendingMode.EXCLUSION
BlendingMode.HARD_LIGHT
BlendingMode.HARD_MIX
BlendingMode.HUE
BlendingMode.LIGHTEN
BlendingMode.LINEAR_BURN
BlendingMode.LINEAR_DODGE
BlendingMode.LINEAR_LIGHT
BlendingMode.LUMINESCENT_PREMULBlendingMode.LUMINOSITY
BlendingMode.MULTIPLY
BlendingMode.NORMAL
8/6/2019 Gua scripting
43/209
43
After Effects Scripting Guide JavaScript Reference
43
BlendingMode.OVERLAY
BlendingMode.PIN_LIGHT
BlendingMode.SATURATION
BlendingMode.SCREEN
BlendingMode.SILHOUETE_ALPHA
BlendingMode.SILHOUETTE_LUMABlendingMode.SOFT_LIGHT
BlendingMode.STENCIL_ALPHA
BlendingMode.STENCIL_LUMA
BlendingMode.VIVID_LIGHT
AVLayer canSetCollapseTransformation attribute
app.project . i tem( index) .canSetCollapseTransformation
Description
True if it is legal to change the value of the col lapseTransformation attribute on this layer.
Type
Boolean; read-only.
AVLayer canSetTimeRemapEnabled attribute
app.project . i tem( index) .canSetTimeRemapEnabled
Description
True if it is legal to change the value of the t imeRemapEnabled attribute on this layer.
Type
Boolean; read-only.
AVLayer collapseTransformation attribute
app.project . i tem( index) .col lapseTransformation
Description
True if collapse transformation is on for this layer.
Type
Boolean; read/write.
AVLayer effectsActive attribute
app.project . i tem( index) .ef fectsAct ive
Description
True if the layer's effects are active, as indicated by the icon next to it in the user interface.
Type
Boolean; read/write.
8/6/2019 Gua scripting
44/209
44
After Effects Scripting Guide JavaScript Reference
44
AVLayer frameBlending attribute
app.project . i tem( index) .frameBlending
Description
True if frame blending is enabled for the layer.
Type
Boolean; read/write.
AVLayer guideLayer attribute
app.project . i tem( index) .guideLayer
Description
True if the layer is a guide layer.
Type
Boolean; read/write.
AVLayer hasAudio attribute
app.project . i tem( index) .hasAudio
Description
True if the layer contains an audio component, regardless of whether it is audio-enabled or solo