Formulas 1.9. Formulas in scripts

In scripts, you can assign numeric expressions to numeric variables, and string expressions to string variables. You can also use numeric and string variables in expressions.

Example: report a square

Choose New Praat script from the Praat menu. A script editor window will become visible. Type the following lines into that window:

x = 99
x2 = x * x
echo The square of 'x' is 'x2'.

This is an example of a simple Praat script; it assigns the results of the numeric formulas 99 and x * x to the numeric variables x and x2. Note that the formula x * x itself refers to the variable x. To run (execute) this script, type Command-R or choose Run from the Run menu. Praat will then write the following text into the Info window:

The square of 99 is 9801.

For more information on scripts, see the Scripting tutorial.

Example: rename the city of Washington

Type the following text into the script editor window:

current$ = "Bush"
previous$ = "Clinton"
famous$ = "Lincoln"
newCapital$ = current$ + mid$ (famous$, 2, 3) + right$ (previous$, 3)
echo The new capital will be 'newCapital$'.

This script assigns the results of four string expressions to the four string variables current$, previous$, famous$, and newCapital$. The dollar sign is the notation for a string variable or for a function whose result is a string (like left$). Note that the formula in the fourth line refers to three existing variables.

To see what the new name of the capital will be, choose Run.

Example: numeric expressions in settings in scripts

As in real settings windows, you can use numeric expressions in all numeric fields. The example of two pages back becomes:

Create Sound from formula... sine Mono 0 10000/44100 44100 0.9 * sin (2*pi*377*x)

If the numeric field is not the last field of the settings window, you will want to write the formula without any spaces, e.g. as 10000/44100, since spaces are used to separate the fields.

Example: string expressions in settings in scripts

As in real settings windows, you cannot use string expressions in text fields directly, but you can still use the trick of variable substitution with single quotes (see Scripting 5.1. Variables):

soundName$ = "hello"
fileName$ = soundName$ + ".wav"
Read from file... 'fileName$'

Example: numeric expressions in creation in scripts

Suppose you want to generate a sine wave whose frequency is held in a variable. This is the way:

frequency = 377
Create Sound from formula... sine Mono 0 1 44100 0.9 * sin (2*pi*frequency*x)

In this example, Praat will protest if x is a variable as well, because that would be ambiguous with the x that refers to the time in the sound (see Formulas 1.8. Formulas for modification).

Links to this page


© ppgb, February 25, 2007