Commands
kid3-cli offers a command-line-interface for Kid3. If a directory path is used, the directory is opened. If one or more file paths are given, the common directory is opened and the files are selected. Subsequent commands will then work on these files. Commands are specified using -c options. If multiple commands are passed, they are executed in the given order. If files are modified by the commands, they will be saved at the end. If no command options are passed, kid3-cli starts in interactive mode. Commands can be entered and will operate on the current selection. The following sections list all available commands.
Help
help [COMMAND-NAME]
Displays help about the parameters of COMMAND-NAME or about all commands if no command name is given.
Timeout
timeout [ default | off | TIME ]
Overwrite the default command timeout. The CLI commands abort after a command specific timeout is expired. This timeout is 10 seconds for ls and albumart, 60 seconds for autoimport and filter, and 3 seconds for all other commands. If a huge number of files has to be processed, this timeouts may be too restrictive, thus the timeout for all commands can be set to TIME ms, switched off altogether or be left at the default values.
Quit application
exit [force]
Exit application. If there are modified unsaved files, the force parameter is required.
Change directory
cd [DIRECTORY]
If no DIRECTORY is given, change to the home directory. If a directory is given, change into the directory. If one or more file paths are given, change to their common directory and select the files.
Print the current working directory
pwd
Print the filename of the current working directory.
Directory list
ls
List the contents of the current directory. This corresponds to the file list in the Kid3 GUI. Five characters before the file names show the state of the file.
-
> File is selected.
-
* File is modified.
-
1 File has a tag 1, otherwise '-' is displayed.
-
2 File has a tag 2, otherwise '-' is displayed.
-
3 File has a tag 3, otherwise '-' is displayed.
kid3-cli> ls 1-- 01 Intro.mp3 > 12- 02 We Only Got This One.mp3 *1-- 03 Outro.mp3
In this example, all files have a tag 1, the second file also has a tag 2 and it is selected. The third file is modified.
Save the changed files
save
Select file
select [ all | none | first | previous | next | FILE... ]
To select all files, enter select all, to deselect all files, enter select none. To traverse the files in the current directory start with select first, then go forward using select next or backward using select previous. Specific files can be added to the current selection by giving their file names. Wildcards are possible, so select *.mp3 will select all MP3 files in the current directory.
kid3-cli> select first kid3-cli> ls > 1-- 01 Intro.mp3 12- 02 We Only Got This One.mp3 *1-- 03 Outro.mp3 kid3-cli> select next kid3-cli> ls 1-- 01 Intro.mp3 > 12- 02 We Only Got This One.mp3 *1-- 03 Outro.mp3 kid3-cli> select *.mp3 kid3-cli> ls > 1-- 01 Intro.mp3 > 12- 02 We Only Got This One.mp3 >*1-- 03 Outro.mp3
Select tag
tag [TAG-NUMBERS]
Many commands have an optional TAG-NUMBERS parameter, which specifies whether the command operates on tag 1, 2, or 3. If this parameter is omitted, the default tag numbers are used, which can be set by this command. At startup, it is set to 12 which means that information is read from tag 2 if available, else from tag 1; modifications are done on tag 2. The TAG-NUMBERS can be set to 1, 2, or 3 to operate only on the corresponding tag. If the parameter is omitted, the current setting is displayed.
Get tag frame
get [ all | FRAME-NAME ] [TAG-NUMBERS]
This command can be used to read the value of a specific tag frame or get information about all tag frames (if the argument is omitted or all is used). Modified frames are marked with a '*'.
kid3-cli> get File: MPEG 1 Layer 3 192 kbps 44100 Hz Joint Stereo Name: 01 Intro.mp3 Tag 1: ID3v1.1 Title Intro Artist One Hit Wonder Album Let's Tag Date 2013 Track Number 1 Genre Pop kid3-cli> get title Intro
To save the contents of a picture frame to a file, use
get picture:'/path/to/folder.jpg'
To save synchronized lyrics to an LRC file, use
get SYLT:'/path/to/lyrics.lrc'
It is possible to get only a specific field from a frame, for example get POPM.Email for the Email field of a Popularimeter frame. If a file has multiple frames of the same kind, the different frames can be indexed with brackets, for example the first performer from a Vorbis comment can be retrieved using get performer[0], the second using get performer[1].
The pseudo field name "selected" can be used to check if a frame is selected, for example get artist.selected will return 1 if the artist frame is selected, else 0.
Set tag frame
set {FRAME-NAME} {FRAME-VALUE} [TAG-NUMBERS]
This command sets the value of a specific tag frame. If FRAME-VALUE is empty, the frame is deleted.
kid3-cli> set remixer 'O.H. Wonder'
To set the contents of a picture frame from a file, use
set picture:'/path/to/folder.jpg' 'Picture Description'
To set synchronized lyrics from an LRC file, use
set SYLT:'/path/to/lyrics.lrc' 'Lyrics Description'
To set a specific field of a frame, the field name can be given after a dot, e.g. to set the Counter field of a Popularimeter frame, use
set POPM.Counter 5
An application for field specifications is the case where you want a custom TXXX frame with "rating" description instead of a standard Popularimeter frame (this seems to be used by some plugins). You can create such a TXXX rating frame with kid3-cli, however, you have to first create a TXXX frame with description "rating" and then set the value of this frame to the rating value.
kid3-cli> set rating "" kid3-cli> set TXXX.Description rating kid3-cli> set rating 5
The first command will delete an existing POPM frame, because if such a frame exists, set rating 5 would set the POPM frame and not the TXXX frame. Another possibility would be to use set TXXX.Text 5, but this would only work if there is no other TXXX frame present.
To set multiple frames of the same kind, an index can be given in brackets, e.g. to set multiple performers in a Vorbis comment, use
kid3-cli> set performer[0] 'Liza don Getti (soprano)' kid3-cli> set performer[1] 'Joe Barr (piano)'
To select certain frames before a copy, paste or remove action, the pseudo field name "selected" can be used. Normally, all frames are selected, to deselect all, use set '*.selected' 0, then for example set artist.selected 1 to select the artist frame.
Revert
revert
Revert all modifications in the selected files (or all files if no files are selected).
Import from file
import {FILE} {FORMAT-NAME} [TAG-NUMBERS]
Tags are imported from the file FILE in the format with the name FORMAT-NAME (e.g. "CSV unquoted", see Import).
If tags is given for FILE, tags are imported from other tags. Instead of FORMAT-NAME parameters SOURCE and EXTRACTION are required, see Import from Tags. To apply the import from tags on the selected files, use tagsel instead of tags. This function also supports output of the extracted value by using an EXTRACTION with the value %{__return}(.+).
Automatic import
autoimport [PROFILE-NAME] [TAG-NUMBERS]
Batch import using profile PROFILE-NAME (see Automatic Import, "All" is used if omitted).
Download album cover artwork
albumart {URL} [all]
Set the album artwork by downloading a picture from URL. The rules defined in the Browse Cover Art dialog are used to transform general URLs (e.g. from Amazon) to a picture URL. To set the album cover from a local picture file, use the set command.
kid3-cli> albumart http://www.amazon.com/Versus-World-Amon-Amarth/dp/B000078DOC
Export to file
export {FILE} {FORMAT-NAME} [TAG-NUMBERS]
Tags are exported to file FILE in the format with the name FORMAT-NAME (e.g. "CSV unquoted", see Export).
Create playlist
playlist
Create playlist in the format set in the configuration, see Create Playlist.
Apply filename format
filenameformat
Apply file name format set in the configuration, see Apply Filename Format.
Apply tag format
tagformat
Apply tag name format set in the configuration, see Apply Tag Format.
Apply text encoding
textencoding
Apply text encoding set in the configuration, see Apply Text Encoding.
Rename directory
renamedir [FORMAT] [ create | rename | dryrun ] [TAG-NUMBERS]
Rename or create directories from the values in the tags according to a given FORMAT (e.g. %{artist} - %{album}, see Rename Directory), if no format is given, the format defined in the Rename directory dialog is used. The default mode is rename; to create directories, create must be given explicitly. The rename actions will be performed immediately, to just see what would be done, use the dryrun option.
Number tracks
numbertracks [TRACK-NUMBER] [TAG-NUMBERS]
Number the selected tracks starting with TRACK-NUMBER (1 if omitted).
Filter
filter [ FILTER-NAME | FILTER-FORMAT ]
Filter the files so that only the files matching the FILTER-FORMAT are visible. The name of a predefined filter expression (e.g. "Filename Tag Mismatch") can be used instead of a filter expression, see Filter.
kid3-cli> filter '%{title} contains "tro"' Started /home/urs/One Hit Wonder - Let's Tag + 01 Intro.mp3 - 02 We Only Got This One.mp3 + 03 Outro.mp3 Finished kid3-cli> ls 1-- 01 Intro.mp3 1-- 03 Outro.mp3 kid3-cli> filter All Started /home/urs/One Hit Wonder - Let's Tag + 01 Intro.mp3 + 02 We Only Got This One.mp3 + 03 Outro.mp3 Finished kid3-cli> ls 1-- 01 Intro.mp3 12- 02 We Only Got This One.mp3 1-- 03 Outro.mp3
Convert ID3v2.3 to ID3v2.4
to24
Convert ID3v2.4 to ID3v2.3
to23
Filename from tag
fromtag [FORMAT] [TAG-NUMBERS]
Set the file names of the selected files from values in the tags, for example fromtag '%{track} - %{title}' 1. If no format is specified, the format set in the GUI is used.
Tag from filename
totag [FORMAT] [TAG-NUMBERS]
Set the tag frames from the file names, for example totag '%{albumartist} - %{album}/%{track} %{title}' 2. If no format is specified, the format set in the GUI is used. If the format of the filename does not match this pattern, a few other commonly used formats are tried.
Tag to other tag
syncto {TAG-NUMBER}
Copy the tag frames from one tag to the other tag, e.g. to set the ID3v2 tag from the ID3v1 tag, use syncto 2.
Copy
copy [TAG-NUMBER]
Copy the tag frames of the selected file to the internal copy buffer. They can then be set on another file using the paste command.
To copy only a subset of the frames, use the "selected" pseudo field with the set command. For example, to copy only the disc number and copyright frames, use
set '*.selected' 0 set discnumber.selected 1 set copyright.selected 1 copy
Paste
paste [TAG-NUMBER]
Set tag frames from the contents of the copy buffer in the selected files.
Remove
remove [TAG-NUMBER]
Remove a tag.
It is possible to remove only a subset of the frames by selecting them as described in the copy command.
Examples
Set title containing an apostrophe. Commands passed to kid3-cli with -c have to be in quotes if they do not only consist of a single word. If such a command itself has an argument containing spaces, that argument has to be quoted too. In UNIX shells single or double quotes can be used, but on the Windows Command Prompt, it is important that the outer quoting is done using double quotes and inside these quotes, single quotes are used. If the text inside the single quotes contains a single quote, it has to be escaped using a backslash character, as shown in the following example:
kid3-cli -c "set title 'I\'ll be there for you'" /path/to/dir
Set album cover in all files of a directory using the batch import function:
kid3-cli -c "autoimport 'Cover Art'" /path/to/dir
Remove comment frames and apply the tag format in both tags of all MP3 files of a directory:
kid3-cli -c "set comment '' 1" -c "set comment '' 2" \ -c "tagformat 1" -c "tagformat 2" /path/to/dir/*.mp3
Automatically import tag 2, synchronize to tag 1, set file names from tag 2 and finally create a playlist:
kid3-cli -c autoimport -c "syncto 1" -c fromtag -c playlist \ /path/to/dir/*.mp3
For all files with an ID3v2.4.0 tag, convert to ID3v2.3.0 and remove the arranger frame:
kid3-cli -c "filter 'ID3v2.4.0 Tag'" -c "select all" -c to23 \ -c "set arranger ''" /path/to/dir
This Python script uses kid3-cli to generate iTunes Sound Check iTunNORM frames from replay gain information.
#!/usr/bin/env python3 # Generate iTunes Sound Check from ReplayGain. import os, sys, subprocess def rg2sc(dirpath): for root, dirs, files in os.walk(dirpath): for name in files: if name.endswith(('.mp3', '.m4a', '.aiff', '.aif')): fn = os.path.join(root, name) rg = subprocess.check_output([ 'kid3-cli', '-c', 'get "replaygain_track_gain"', fn]).strip() if rg.endswith(b' dB'): rg = rg[:-3] try: rg = float(rg) except ValueError: print('Value %s of %s in not a float' % (rg, fn)) continue sc = (' ' + ('%08X' % int((10 ** (-rg / 10)) * 1000) )) * 10 subprocess.call([ 'kid3-cli', '-c', 'set iTunNORM "%s"' % sc, fn]) if __name__ == '__main__': rg2sc(sys.argv[1])
JSON Format
In order to make it easier to parse results from kid3-cli, it is possible to get the output in JSON format. When the request is in JSON format, the response will also be JSON. A compact format of the request will also give a compact representation of the response. If the request contains an "id" field, it is assumed to be a JSON-RPC request and the response will contain a "jsonrpc" field and the "id" of the request. The request format uses the same commands as the standard CLI, the "method" field contains the command and the parameters (if any) are given in the "params" list. The response contains a "result" object, which can also be null if the corresponding kid3-cli command does not return a result. In case of an error, an "error" object is returned with "code" and "message" fields as used in JSON-RPC.
kid3-cli> {"method":"set","params":["artist","An Artist"]} {"result":null} kid3-cli> {"method":"get","params":["artist",2]} {"result":"An Artist"} kid3-cli> {"method": "get", "params": ["artist"]} { "result": "An Artist" } kid3-cli> {"jsonrpc":"2.0","id":"123","method":"get","params":["artist"]} {"id":"123","jsonrpc":"2.0","result":"An Artist"}
QML scripts can be invoked via the context menu of the file list and can be set in the User Actions tab of the settings dialog. The scripts which are set there can be used as examples to program custom scripts. QML uses JavaScript, here is the obligatory "Hello World":
import Kid3 1.0 Kid3Script { onRun: { console.log("Hello world, directory is", app.dirName) Qt.quit() } }
Or, in the console:
console.log("Hello world, directory is", app.dirName) script.properties(app) console.log(script.properties(app))
If this script is saved as /path/to/Example.qml, the user command can be defined as @qml /path/to/Example.qml with name QML Test and Output checked. It can then be started using the QML Test item in the file list context menu, and the output will be visible in the window. Alternatively, the script could also be started independent of Kid3 using the QML tools.
qml -apptype widget -I /usr/lib/kid3/plugins/imports /path/to/Example.qml
or
qmlscene -I /usr/lib/kid3/plugins/imports /path/to/Example.qml
On Windows and OSX, the import path must be adapted to the imports folder inside the installation directory. Scripts started outside of Kid3 will use the current directory, so it should be changed beforehand.
To list the titles in the tags 2 of all files in the current directory, the following script could be used:
import Kid3 1.0 Kid3Script { onRun: { app.firstFile() do { if (app.selectionInfo.tag(Frame.Tag_2).tagFormat) { console.log(app.getFrame(tagv2, "title")) } } while (app.nextFile()) } }
If the directory contains many files, such a script might block the user interface for some time. For longer operations, it should therefore have a break from time to time. The alternative implementation below has the work for a single file moved out into a function. This function invokes itself with a timeout of 1 ms at the end, given that more files have to be processed. This will ensure that the GUI remains responsive while the script is running.
import Kid3 1.0 Kid3Script { onRun: { function doWork() { if (app.selectionInfo.tag(Frame.Tag_2).tagFormat) { console.log(app.getFrame(tagv2, "title")) } if (!app.nextFile()) { Qt.quit() } else { setTimeout(doWork, 1) } } app.firstFile() doWork() } }
When using app.firstFile() with app.nextFile(), all files of the current directory will be processed. If only the selected files shall be affected, use firstFile() and nextFile() instead, these are convenience functions of the Kid3Script component. The following example is a script which copies only the disc number and copyright frames of the selected file.
import Kid3 1.1 Kid3Script { onRun: { function doWork() { if (app.selectionInfo.tag(Frame.Tag_2).tagFormat) { app.setFrame(tagv2, "*.selected", false) app.setFrame(tagv2, "discnumber.selected", true) app.setFrame(tagv2, "copyright.selected", true) app.copyTags(tagv2) } if (!nextFile()) { Qt.quit() } else { setTimeout(doWork, 1) } } firstFile() doWork() } }
More example scripts come with Kid3 and are already registered as user commands.
- ReplayGain to SoundCheck (ReplayGain2SoundCheck.qml): Create iTunNORM SoundCheck information from replay gain frames.
- Resize Album Art (ResizeAlbumArt.qml): Resize embedded cover art images which are larger than 500x500 pixels.
- Extract Album Art (ExtractAlbumArt.qml): Extract all embedded cover art pictures avoiding duplicates.
- Embed Album Art (EmbedAlbumArt.qml): Embed cover art found in image files into audio files in the same folder.
- Embed Lyrics (EmbedLyrics.qml): Fetch unsynchronized lyrics from web service.
- Text Encoding ID3v1 (ShowTextEncodingV1.qml): Helps to find the encoding of ID3v1 tags by showing the tags of the current file in all available character encodings.
- Export CSV (ExportCsv.qml): Export recursively all tags of all files to a CSV file.
- Export Playlist Folder (ExportPlaylist.qml): Copy all files from a playlist into a directory and rename them according to their position.
- QML Console (QmlConsole.qml): Simple console to play with Kid3's QML API.
QML API
The 3 APIs can be easily explored using the QML Console. There are 3 root objects: SCRIPT, APP, and CONFIGS.
Kid3Script
Kid3Script is a regular QML component located inside the plugin directory. You could use another QML component just as well. Using Kid3Script makes it easy to start the script function using the onRun signal handler. Moreover it offers some functions:
onRun: Signal handler which is invoked when the script is started tagv1, tagv2, tagv2v1: Constants for tag parameters script: Access to scripting functions configs: Access to configuration objects getArguments(): List of script arguments isStandalone(): true if the script was not started from within Kid3 setTimeout(callback, delay): Starts callback after delay ms firstFile(): To first selected file nextFile(): To next selected file
Scripting Object Model
JavaScript, and therefore QML too, has only a limited set of functions for scripting. Therefore, the script object has been added to kid3 and has some additional methods:
script.properties(obj) script.writeFile(filePath, data) script.readFile(filePath) script.removeFile(filePath) script.fileExists(filePath) script.fileIsWritable(filePath) script.getFilePermissions(filePath) script.setFilePermissions(filePath, modeBits) script.classifyFile(filePath): Get class of file (dir "/", symlink "@", exe "*", file " ") script.renameFile(oldName, newName): Rename file, true if OK script.copyFile(source, dest): Copy file, true if OK script.makeDir(path): Create directory, true if OK script.removeDir(path): Remove directory, true if OK script.tempPath(): Path to temporary directory script.musicPath(): Path to music directory script.listDir(path, [nameFilters], [classify]): List directory entries script.system(program, [args], [msecs]): Synchronously start a system command, [exit code, standard output, standard error] if not timeout script.systemAsync(program, [args], [callback]): Asynchronously start a system command, callback will be called with [exit code, standard output, standard error] script.getEnv(varName): Get value of environment variable script.setEnv(varName, value): Set value of environment variable script.getQtVersion(): Qt version string, e.g. "5.4.1" script.getDataMd5(data): Get hex string of the MD5 hash of data script.getDataSize(data): Get size of byte array script.dataToImage(data, [format]): Create an image from data bytes script.dataFromImage(img, [format]): Get data bytes from image script.loadImage(filePath): Load an image from a file script.saveImage(img, filePath, [format]): Save an image to a file, true if OK script.imageProperties(img): Get properties of an image, map containing "width", "height", "depth" and "colorCount", empty if invalid image script.scaleImage(img, width, [height]): Scale an image, returns scaled image
Application Object Model
Using QML, a large part of the Kid3 functions are accessible. The API is similar to the one used for D-Bus.
app.openDirectory(path): Open directory app.unloadAllTags(): Unload all tags app.saveDirectory(): Save directory app.revertFileModifications(): Revert app.importTags(tag, path, fmtIdx): Import file app.importFromTags(tag, source, extraction): Import from tags app.importFromTagsToSelection(tag, source, extraction): Import from tags of selected files app.downloadImage(url, allFilesInDir): Download image app.exportTags(tag, path, fmtIdx): Export file app.writePlaylist(): Write playlist app.getPlaylistItems(path): Get items of a playlist app.setPlaylistItems(path, items): Set items of a playlist app.selectAllFiles(): Select all app.deselectAllFiles(): Deselect app.firstFile([select], [onlyTaggedFiles]): To first file app.nextFile([select], [onlyTaggedFiles]): To next file app.previousFile([select], [onlyTaggedFiles]): To previous file app.selectCurrentFile([select]): Select current file app.selectFile(path, [select]): Select a specific file app.getSelectedFilePaths([onlyTaggedFiles]): Get paths of selected files app.requestExpandFileList(): Expand all app.applyFilenameFormat(): Apply filename format app.applyTagFormat(): Apply tag format app.applyTextEncoding(): Apply text encoding app.numberTracks(nr, total, tag, [options]): Number tracks app.applyFilter(expr): Filter app.convertToId3v23(): Convert ID3v2.4.0 to ID3v2.3.0 app.convertToId3v24(): Convert ID3v2.3.0 to ID3v2.4.0 app.getFilenameFromTags(tag): Filename from tags app.getTagsFromFilename(tag): Filename to tags app.getAllFrames(tag): Get object with all frames app.getFrame(tag, name): Get frame app.setFrame(tag, name, value): Set frame app.getPictureData(): Get data from picture frame app.setPictureData(data): Set data in picture frame app.copyToOtherTag(tag): Tags to other tags app.copyTags(tag): Copy app.pasteTags(tag): Paste app.removeTags(tag): Remove app.playAudio(): Play app.readConfig(): Read configuration app.applyChangedConfiguration(): Apply configuration app.dirName: Directory name app.selectionInfo.fileName: File name app.selectionInfo.filePath: Absolute file path app.selectionInfo.detailInfo: Format details app.selectionInfo.tag(Frame.Tag_1).tagFormat: Tag 1 format app.selectionInfo.tag(Frame.Tag_2).tagFormat: Tag 2 format app.selectionInfo.formatString(tag, format): Substitute codes in format string app.selectFileName(caption, dir, filter, saveFile): Open file dialog to select a file app.selectDirName(caption, dir): Open file dialog to select a directory
For asynchronous operations, callbacks can be connected to signals.
function automaticImport(profile) { function onAutomaticImportFinished() { app.batchImporter.finished.disconnect(onAutomaticImportFinished) } app.batchImporter.finished.connect(onAutomaticImportFinished) app.batchImport(profile, tagv2) } function renameDirectory(format) { function onRenameActionsScheduled() { app.renameActionsScheduled.disconnect(onRenameActionsScheduled) app.performRenameActions() } app.renameActionsScheduled.connect(onRenameActionsScheduled) app.renameDirectory(tagv2v1, format, false) }
Configuration Object Model
Configuration properties are mostly read/write. You can use script.properties() to get inner classes.
configs.networkConfig() configs.networkConfig().useProxy configs.batchImportConfig() configs.exportConfig() configs.fileConfig() configs.filenameFormatConfig() configs.filterConfig() configs.findReplaceConfig() configs.guiConfig() configs.importConfig() configs.mainWindowConfig() configs.networkConfig() configs.numberTracksConfig() configs.playlistConfig() configs.renDirConfig() configs.tagConfig() configs.tagFormatConfig() configs.userActionsConfig()