# Scripting

### From Audacity Development Manual

The scripting module is an experimental GUI plug-in that allows Audacity to be driven from an external Perl script. Commands are sent to Audacity over a named pipe. Any scripting language that supports named pipes can be used in place of Perl. External scripting is one of several ways to extend the functionality of Audacity.

| Scripting support is currently considered experimental and is mainly intended for use by developers for the time being. Feel free to try it out, but don't be too surprised if there are problems.

## How to get started with scripting

Audacity can currently only be used with scripting if you compile a separate plug-in module from our Git sources called "mod-script-pipe", as well as compile Audacity itself. See the Wiki Developer Guide for help. You'll also need the scripting language Perl to try out the examples. For actually writing scripts however, any language that can write to and read from a named pipe should be able to use the interface.

We may provide a ready-compiled mod-script-pipe at some future time. If you just want to use scripting but don't want to do the developer steps then you will need to wait for that to be released. Feel free to let us know if you would like ready-to-go scripting in Audacity, and what you would use it for.

### Building

Ensure you have the latest Git version of Audacity built, installed and working. The scripting module, "mod-script-pipe" is in Git (under lib-src), but is not built automatically.

In MSVC, open "mod-script-pipe.vcproj" and build. If all goes to plan, the DLL will be placed in the "modules" directory.

Under GCC, move into the lib-src/mod-script-pipe directory and type "make". This will build the module then copy "mod-script-pipe.so" to the "modules" directory in the source code tree. To have Audacity see mod-script-pipe.so, copy it to /usr/local/share/audacity/modules or ~/.audacity-files/modules/.

While mod-script-pipe allows a script to communicate with Audacity, it is not concerned with the actual interpretation and processing of received commands. That is done by Audacity itself, so for full scripting capabilities it is important to have a recent build of the main program as well as the scripting module.

### Testing

A basic test script "scripts/pipe-test.pl" is included in the development repository. Naturally, this requires Perl. It contains a variety of tests and subroutines for sending commands on the pipe.

The test script exports audio files to (and imports them from) a ~/pipetest/ directory which you will need to create.

Launch Audacity first, then execute the test script.

If everything is fine, the commands in the script will be sent to Audacity, executed, and the results sent back to the script.

You can experiment with changing the commands in the script (see below).

If the script hangs, waiting for a response, it probably means that Audacity did not load the scripting module. Examine the logging output to check if this is the case.

If the module was notloaded, it could be because it has not been placed in the correct directory or because the module version does not match the version of Audacity. The surest way to avoid this problem is to build both Audacity and mod-script-pipe from HEAD at the same time.

## Commands

Some documentation for the parts of Audacity that can currently be controlled via script command follows. Be aware that this is likely to change significantly until scripting has matured. Note also that commands and parameters are case-sensitive.

The command invocations should take the following form:

`Command: Param1=Value1 Param2=Value2` | ``

This is followed by a line break. Then the command is executed, and any responses are written on the return pipe, on separate lines. The end of the responses is signalled by an empty line. Further commands should not be sent until all responses have been read.

- See also additional commands on the Audacity Wiki.

### BatchCommand

This can be invoked differently from the other commands because, at the moment, all unrecognized commands are treated as batch commands. To see what these commands do and how they should be formed, please examine the Edit Chains dialog. As an example, the batch system can be used to apply an effect to some selected audio.

It is also possible to explicitly call a batch command, but be aware that it is not currently possible for a parameter value to contain spaces, so this way of doing it is fairly restricted. If ChainName is provided, the command applies the saved batch chain of that name rather than a single command.

Parameters:

ChainName: | If provided, applies the batch chain of that name

CommandName: | Name of the batch command to execute

ParamString: | Parameters for the batch command

Examples:

Send | Receive

`BatchCommand: CommandName=Noise` | `BatchCommand finished: OK`

`ChangeTempo: Percentage=10.0` | `BatchCommand finished: OK`

### CompareAudio

With two tracks selected, running this command compares the tracks sample by sample, and counts the number of samples whose absolute difference exceeds the given threshold. The total count is returned, as well as the number of seconds of audio that these samples represent.

Parameters:

Threshold: | Floating point number 0.0 to 1.0

Example:

Send | Receive

`CompareAudio: Threshold=0.1` | `Comparing tracks 'Audio Track 1' and 'Audio Track 2'. Finished comparison: 764480 samples (17.335 seconds) exceeded the error threshold of 0.200000. CompareAudio finished: OK`

### MenuCommand

Executes a 'menu command', using the system that controls the Audacity menus. This is simple but powerful, and many of the tasks that can be performed by clicking menu items or pressing shortcuts can also be triggered by a script using this command. Use GetAllMenuCommands to see a full list of available commands.

Parameters:

CommandName: | Name of the menu command to execute

Examples:

Send | Receive

`MenuCommand: CommandName=SplitDelete` | `MenuCommand finished: OK`

`MenuCommand: CommandName=Play` | `MenuCommand finished: OK`

`MenuCommand: CommandName=TrackMute` | `MenuCommand finished: OK`

### GetAllMenuCommands

Returns a list of all available menu commands. These are the commands that can be sent using MenuCommand.

No parameters.

### GetTrackInfo

Allows information about a project's tracks to be returned to the script.

Parameters:

TrackIndex: | An integer (default: 0) identifying the track

Type: | Info to get. One of: Name, StartTime, EndTime (default: Name)

Examples:

Send | Receive

`GetTrackInfo: Type=Name TrackIndex=0` | `Audio Track GetTrackInfo finished: OK`

`GetTrackInfo: Type=EndTime TrackIndex=0` | `24.000000 GetTrackInfo finished: OK`

### Help

Returns information about the parameters accepted by a given command.

Parameters:

CommandName: | The command on which to get help

Example:

Send | Receive

`Help: CommandName=Select` | `Select Parameters: EndTime: a floating-point number (default: 0) FirstTrack: an integer (default: 0) LastTrack: an integer (default: 0) Mode: one of: None, All, Range, Name (default: All) StartTime: a floating-point number (default: 0) TrackName: any value (default: 0) Help finished: OK`

### Message

Sends a message to the command's status target. Since command status messages are currently sent to the script (if the command was triggered by a script), this means the message is sent back to the script.

Parameters:

MessageString: | The message to send

Example:

Send | Receive

`Message: MessageString=hello` | `hello Message finished: OK`

### Screenshot

The screenshot command is modelled closely on the Screenshot Tools dialog and takes three parameters.

Parameters:

FilePath: | A string representing the directory path in which the captured images should be saved.

CaptureMode: | A string specifying which area of the screen should be captured. Possible values: window, fullwindow, windowplus, fullscreen, toolbars, selectionbar, tools, control, mixer, meter, edit, device, transcription, trackpanel, ruler, tracks, firsttrack, secondtrack.

Background: | Type of background to use in the shots where one is possible. Possible values: White, Blue, None.

Example:

Send | Receive

`Screenshot: FilePath=/home/dan/Temp CaptureMode=fullwindow Background=None` | `Saved /home/dan/Temp/fullwindow001.png Screenshot finished: OK`

### Select

Provides some control over the project selection. Tracks between FirstTrack and LastTrack inclusive are selected, and the time interval selected is from StartTime to EndTime. Alternatively, if TrackName is specified, then the track with that name is selected.

Parameters:

FirstTrack: | An integer (default: 0)

LastTrack: | An integer (default: 0)

TrackName: | Name of a track (not required if using FirstTrack and LastTrack)

StartTime: | A floating-point number (default: 0)

EndTime: | A floating-point number (default: 0)

Mode: | One of: None, All, Range, Name (default: All)

Example:

Send | Receive

`Select: Mode=Range FirstTrack=0 LastTrack=1 StartTime=3.2 EndTime=8.4` | `Selected track 'Audio Track 1' Selected track 'Audio Track 2' Select finished: OK`

`Select: Mode=Range FirstTrack=0 LastTrack=0 StartTime=0.1 EndTime=9.9` | `Selected track 'Audio Track 1' Select finished: OK`

### GetPreference

Prints the value of the requested preference as a response.

Parameters:

PrefName: | String containing the name of the preference (as in audacity.cfg)

Example:

Send | Receive

`GetPreference: PrefName=/CsPresets/NoiseGen_Duration` | `30 GetPreference finished: OK`

### SetPreference

Sets the preference with the given name to the given value.

Parameters:

PrefName: | String containing the name of the preference (as in audacity.cfg)

PrefValue: | Value of the preference

Example:

Send | Receive

`SetPreference: PrefName=/CsPresets/NoiseGen_Duration PrefValue=12.0` | `SetPreference finished: OK`

### SetTrackInfo

For setting track information - currently track name only. (Note mute/solo can be set with menu commands)

Parameters:

TrackIndex: | Specifies which track to modify

Type: | Type of info to set - currently 'Name' is the only option

Name: | String to which the track name is to be set

Example:

Send | Receive

`SetTrackInfo: TrackIndex=0 Type=Name Name=Eric` | `SetTrackInfo finished: OK`

### Import

Load audio data from a file into a track. The file type is detected from the extension, and any format understood by Audacity can be used.

Parameters:

Filename: | Name of the file to import

Example:

Send | Receive

`Import: Filename=/home/dan/ArtTatum-Indiana.flac` | `Import finished: OK`

### OpenProject

Opens an audacity project file, optionally from a supplied file name. If the Filename parameter is omitted or empty the user is prompted to choose a project to open. Note that if the current project is not empty and unsaved, a new project window is opened, which may break your script.

Parameters:

Filename: | File name of the project to open. Default is to prompt the user to choose a file. Must include .aup file extension. default=ask user

AddToHistory: | Include opened file in File -> Recent Files? Has no effect on User prompted files; they always appear in Recent Files. default=yes

Example:

Send | Receive

`OpenProject: Filename=myproject.aup` | `OpenProject finished: OK`

### SaveProject

Saves an Audacity project file, optionally to a supplied file name. If the Filename parameter is omitted or empty the user is prompted to choose a saved file. Note: trying to overwrite another existing project will result in an error message to the user.

Parameters:

Filename: | File name of the project to save to. Default is to prompt the User to choose a file. Must include .aup file extension. default=ask user

Compress: | Save audio in compressed (OGG) format? default=no

AddToHistory: | Include opened file in File -> Recent Files? Has no effect on User prompted files; they always appear in Recent Files. default=yes

Example:

Send | Receive

`SaveProject: Filename=myproject.aup` | `SaveProject finished: OK`

### Export

Save audio from the project into a file. The file type to export to is detected from the extension, and any format understood by Audacity can be used.

Parameters:

Mode: | Either 'All' or 'Selection' - sets which audio is to be exported

Filename: | File to export to

Channels: | Number of channels to export

Example:

Send | Receive

`Export: Mode=All Filename=/home/dan/ArtTatum-Indiana.mp3 Channels=2` | `Exported to MP3 format: /home/dan/ArtTatum-Indiana.mp3 Export finished: OK`

## Adding Commands to Audacity (for developers)

For a command to be callable from a script, a CommandType object for it must be added to the CommandDirectory, which is a singleton class. A CommandType has the job of creating specific Command objects, which actually do the work.

To implement a new command called Foo, it is simplest to create new classes FooCommandType and FooCommand which derive from CommandType and CommandImplementation respectively, and then override the virtual methods as appropriate. Then add an instance of FooCommandType to the CommandDirectory.

In the future, the repetitive nature of some of this code may be reduced, for example by using macros (as in wxwidgets). For more information on the workings of the command system, see the source code - in particular the files in the src/commands directory.

## Known Issues & Missing Features

- Parameters to BatchCommand cannot currently contain spaces.
- Scripting only works with one project at a time.
- For some menu commands, the project window must have focus for the command to succeed.
- Scripts have no control over the type and verbosity of responses they receive. (Related: it's not straightforward to get 'output' responses from commands like GetTrackInfo.)
- Current commands could have stricter parameter validation.
- There's no consistent way to abort or interrupt commands.
- There are still many parts of Audacity that cannot currently be controlled from a script because commands for them have not yet been created.
- Due to a slight problem with module management, the scripting module is not unloaded when Audacity quits. This means the script pipes are not properly deleted.
- There may or may not be security problems relating to the use of pipes. You're advised not to use mod-script-pipe on a system with multiple simultaneous users.
- The interface on the script side of the pipe is still quite low-level. It may be possible to generate libraries for specific scripting languages from the internal descriptions of the commands.

##### Views

##### Useful External Links

- Forum
- Wiki
- Latest Release