fb
Functions for controlling foobar2000 and accessing it's data.
Functions for controlling foobar2000 and accessing it's data.
AlwaysOnTop: boolean
fb.AlwaysOnTop = !fb.AlwaysOnTop; // Toggles the current value.
ComponentPath: string
console.log(fb.ComponentPath); // C:\Users\User\AppData\Roaming\foobar2000\user-components\foo_uie_jsplitter\
CursorFollowPlayback: boolean
CustomVolume: boolean
It can be used for displaying the volume from UPnP devices.
It will return a value of -1 when using a normal device and that also indicates that fb.Volume is writable.
When a custom volume control is active, you can not use fb.Volume and must use fb.VolumeUp / fb.VolumeDown / fb.VolumeMute.
FoobarPath: string
IsPaused: boolean
IsPlaying: boolean
PlaybackFollowCursor: boolean
PlaybackLength: float
console.log(fb.PlaybackLength); // 322.843414966166console.log(Math.round(fb.PlaybackLength)); // 323
PlaybackTime: float
fb.PlaybackTime = 60; // Jumps to the 1 minute mark.
ProfilePath: string
ReplaygainMode: number
0 - None
1 - Track
2 - Album
3 - Track/Album by Playback Order (only available in foobar2000 v1.3.8 and later) See ReplayGainMode enum
Error — If the assigned value is not a valid replay gain mode.
StopAfterCurrent: boolean
fb.StopAfterCurrent = !fb.StopAfterCurrent; // Toggles the current value.
Version: string
console.log(fb.Version)
// 1.4.1
Volume: float
fb.Volume = 0; // Sets the volume to max. -100 is the minimum.
Window: FbWindow
Access to the main foobar2000 application window. See FbWindow for global state, multi-panel ownership and UI-specific behavior.
AcquireUiSelectionHolder()
AddDirectory()
AddFiles()
AddLocationsAsync(locations)
Converts one or more paths to a list of metadb_handles.
The function returns immediately; specified callback on_locations_added receives results when the operation has completed.
Relative filesystem paths are resolved as described in utils.ReadTextFile. URLs and foobar2000 URI paths are passed through unchanged. Each filesystem location is resolved before the asynchronous operation starts.
| Name | Type | Description |
|---|---|---|
locations | Array<string> | must be an array of strings and it can contain file paths, playlists or urls. |
number — task id (see first parameter of on_locations_added)
Error — If called before foobar2000 is fully initialized.
function on_mouse_lbtn_dblclk() {
var files = ["z:\\1.mp3", "z:\\2.flac"];
var task_id = fb.AddLocationsAsync(files);
console.log("got task_id", task_id);
}
function on_locations_added(task_id, handle_list) {
console.log("callback task_id", task_id);
console.log(handle_list.Count);
}
CheckClipboardContents()
Checks Clipboard contents are handles or a file selection from Windows Explorer. Use in conjunction with fb.GetClipboardContents.
booleanClearPlaylist()
Clears active playlist.
If you wish to clear a specific playlist, use plman.ClearPlaylist(playlistIndex).
CopyHandleListToClipboard(handle_list)
Note: items can then be pasted in other playlist viewers or in Windows Explorer as files.
| Name | Type | Description |
|---|---|---|
handle_list | FbMetadbHandleList |
booleanError — If handle_list is null.
let handle_list = plman.GetPlaylistSelectedItems(plman.ActivePlaylist);
fb.CopyHandleListToClipboard(handle_list);let ap = plman.ActivePlaylist;
if (!plman.GetPlaylistLockedActions(ap).includes('RemoveItems')) {
let handle_list = plman.GetPlaylistSelectedItems(ap);
if (fb.CopyHandleListToClipboard(handle_list)) {
plman.UndoBackup(ap);
plman.RemovePlaylistSelection(ap);
}
}
CreateContextMenuManager()
CreateHandleList()
Returns an empty handle list.
Deprecated: use FbMetadbHandleList constructor instead.
CreateMainMenuManager()
CreateProfiler(name)
| Name | Type | Description |
|---|---|---|
name = ''optional | string | Will be shown in console when used with Print method. |
DoDragDrop(window_id, handle_list, effect, options)
Invokes drag-n-drop operation (see https://docs.microsoft.com/en-us/windows/win32/api/ole2/nf-ole2-dodragdrop).
Quick tips:
- If you need only to drag from your panel with copy (i.e. without physically moving them): use only fb.DoDragDrop(handles, DROPEFFECT_COPY | DROPEFFECT_LINK).
- If you need only to receive drop to your panel with copy: handle on_drop_*() callbacks, while setting action.effect argument to (DROPEFFECT_COPY | DROPEFFECT_LINK).
Full drag-n-drop interface description:
- Drag-n-drop interface is based on Microsoft IDropSource and IDropTarget interfaces, so a lot of info (including examples) could be gathered from MSDN (IDropSource, IDropTarget, DoDragDrop, DROPEFFECT).
- Drag operation is started with DoDragDrop (whether it is called by your panel, or externally) with okEffects argument supplied.
- DoDragDrop blocks code execution until the drag operation is finished (callbacks will be called properly though). It returns effect from Action.Effect from on_drag_drop after completion.
- (Spider Monkey Panel specific) Drag operation is canceled when any mouse button is pressed.
- (Spider Monkey Panel specific) All mouse callbacks are suppressed during drag operation (including on_mouse_lbtn_up, but excluding on_mouse_mbtn_up and on_mouse_rbtn_up).
- Every drag callback receives Action argument. Action.Effect contains okEffects from DoDragDrop call. Action.Effect should be changed to the desired effect in the callback. If the returned Action.Effect was not in okEffects or is equal to DROPEFFECT_NONE (=== 0), then drop will be denied: cursor icon will be changed, on_drag_drop won't be called after releasing lmbtn, on_drag_leave will be called instead.
- DROPEFFECT_LINK should be used as fallback in case effect argument does not have DROPEFFECT_COPY (===1), since some external drops only allow DROPEFFECT_LINK effect.
- Changing effect on key modifiers is nice (to be in line with native Windows behaviour): see the example below.
Note: due to the asynchronous nature of event handling, fb.DoDragDrop might exit before on_drag_drop callback is triggered when dropping data on the same panel as the one that had a call to fb.DoDragDrop.
Related callbacks: on_drag_enter, on_drag_drop, on_drag_over, on_drag_leave
| Name | Type | Description |
|---|---|---|
window_id | number | unused |
handle_list | FbMetadbHandleList | |
effect | number | Allowed effects. |
options = undefinedoptional | object | Customization options for the data displayed in the drag window. |
options.show_text = trueoptional | boolean | If true, will add track count text. |
options.use_album_art = trueoptional | boolean | If true, will use album art of the focused item from dragged tracks (if available) |
options.use_theming = trueoptional | boolean | If true, will use Windows drag window style. Album art and custom image are resized to fit when Windows style is active. |
options.custom_image = undefinedoptional | GdiBitmap | (or D2DBitmap if window.DrawMode == 1). Custom dragging image. Will be also displayed if use_album_art is true, but there is no album art available. |
number — Effect that was returned in on_drag_drop.
Error — If handle_list is null, options is not an object, or the panel host is not fully initialized.
EnableAdvancedLogging()
For future development purposes (e.g. verbose console output)
EnumerateMainMenuCommands()
Returns all main menu items recursivley.
It is a JSON array in string form so you need to use JSON.parse on the result.
Every item of the array is object with the following properties:
Checked: boolean
Disabled: boolean
FullPath: string, the same full path you'd supply to fb.RunMainMenuCommand
HiddenByDefault: boolean
Radio: boolean
Type: string ("Fixed" or "Dynamic")
Visible: boolean
stringconst menuCommands = JSON.parse(fb.EnumerateMainMenuCommands());
// list all checked commands in the console
menuCommands
.filter(command => command.Checked)
.forEach(({ FullPath }) => console.log(FullPath));
Exit()
GetActiveDSPs()
Returns array of active DSPs names.
Array<string>GetAudioChunk(requested_length, offset)
Returns PCM data from the foobar2000 visualisation stream.
The stream is created lazily. A negative offset requests data before the current visualisation time; JSplitter automatically maintains the native backlog required for that offset. The first stream initialization may briefly synchronize with the foobar2000 main thread.
For repeated real-time processing, prefer fb.GetAudioChunkTo to write directly into a reusable Float32Array without creating a transient FbAudioChunk. CopyDataTo remains useful when a chunk object is already required, while Data preserves its legacy allocating Array behaviour for compatibility.
| Name | Type | Description |
|---|---|---|
requested_length | number | |
offset = 0optional | number |
Error — If the foobar2000 visualisation stream cannot be created.
GetAudioChunkTo(destination, requested_length, offset, info)
Writes interleaved PCM samples from the foobar2000 visualisation stream directly into an existing Float32Array. Unlike fb.GetAudioChunk, this method does not create an FbAudioChunk; after the first sufficiently large native scratch buffer has been established, repeated calls can reuse both the native scratch storage and the JavaScript destination buffer.
A negative offset has the same backlog semantics as fb.GetAudioChunk. If info is supplied, it is updated in place with SampleCount, ChannelCount, SampleRate and ChannelConfig.
| Name | Type | Description |
|---|---|---|
destination | Float32Array | Destination buffer. It must have room for all interleaved PCM sample values. |
requested_length | number | |
offset = 0optional | number | |
infooptional | Object | Reusable metadata object updated in place. |
number — Number of scalar PCM samples written, or 0 when no chunk is currently available.
Error — If the foobar2000 visualisation stream cannot be created, destination is not a Float32Array or is too small, or info is not an object.
GetAudioStreams(handle)
Returns the audio streams exposed by the input decoder for handle as array of AudioStreamInfo objects.
Returns an empty array when the file's input decoder does not expose stream information. Related methods: fb.SetAudioStream.
| Name | Type | Description |
|---|---|---|
handle | FbMetadbHandle |
Array<AudioStreamInfo>Error — If handle is null or foobar2000's input stream selector is unavailable.
const handle = fb.GetFocusItem();
if (handle) {
const streams = fb.GetAudioStreams(handle);
for (const stream of streams) {
console.log(`#${stream.index}: default=${stream.default}, selected=${stream.selected}`);
for (let i = 0; i < stream.info.InfoCount; ++i) {
console.log(` ${stream.info.InfoName(i)}=${stream.info.InfoValue(i)}`);
}
}
}
GetClipboardContents(window_id)
Note: clipboard contents can be handles copied to the clipboard in other components, from fb.CopyHandleListToClipboard or a file selection, from Windows Explorer and etc.
Performance note: validate clipboard content with fb.CheckClipboardContents before calling this method.
| Name | Type | Description |
|---|---|---|
window_id = 0optional | number | unused |
Error — If called before foobar2000 is fully initialized.
function on_mouse_rbtn_up(x, y) {
let ap = plman.ActivePlaylist;
let menu = window.CreatePopupMenu();
menu.AppendMenuItem(!plman.GetPlaylistLockedActions(ap).includes('AddItems') && fb.CheckClipboardContents() ? MF_STRING : MF_GRAYED, 1, "Paste"); // see Flags.js for MF_* definitions
let idx = menu.TrackPopupMenu(x, y);
if (idx == 1) {
let handle_list = fb.GetClipboardContents();
plman.InsertPlaylistItems(ap, plman.PlaylistItemCount(ap), handle_list );
}
return true;
}
GetDSPPresets()
Available only in foobar2000 v1.4 and above. Throws a script error on v1.3. *
Returns a JSON array in string form so you need to use JSON.parse() on the result.
Related methods: fb.SetDSPPreset.
stringlet str = fb.GetDSPPresets();
let arr = JSON.parse(str);
console.log(JSON.stringify(arr, null, 4));
// [
// {
// "active": false,
// "name": "High Filter"
// },
// {
// "active": true,
// "name": "R128 Compressor"
// },
// {
// "active": false,
// "name": "7.1 upmix"
// }
// ]
GetFocusItem(force)
| Name | Type | Description |
|---|---|---|
force = trueoptional | boolean | When true, it will use the first item of the active playlist if it is unable to get the focus item. |
GetLibraryItems()
Returns all Media Library items as a handle list.
GetLibraryRelativePath(handle)
Note: do not use this while looping through a handle list. Use GetLibraryRelativePaths instead.
Returns an empty string when used on track not in Media Library
| Name | Type | Description |
|---|---|---|
handle | FbMetadbHandle |
stringError — If handle is null.
// The foobar2000 Media Library is configured to watch "D:\Music" and the
// path of the now playing item is "D:\Music\Albums\Artist\Some Album\Some Song.flac"
let handle = fb.GetNowPlaying();
console.log(fb.GetLibraryRelativePath(handle)); // Albums\Artist\Some Album\Some Song.flac*
GetLibraryRoots()
Returns unique Media Library root paths inferred from the current Media Library contents.
Each root is reconstructed from the absolute path and library-relative path of a library item.
Configured library folders that contain no library items cannot be returned.
Array<string> — Media Library root paths
GetNowPlaying()
Get handle of the now playing track.
?FbMetadbHandle — null, if nothing is being played.
GetOutputDevices()
Available only in foobar2000 v1.4 and above. Throws a script error on v1.3. *
Returns a JSON array in string form so you need to use JSON.parse() on the result.
Related methods: fb.SetOutputDevice.
stringlet str = fb.GetOutputDevices();
let arr = JSON.parse(str);
console.log(JSON.stringify(arr, null, 4));
// [
// {
// "active": false,
// "device_id": "{5243F9AD-C84F-4723-8194-0788FC021BCC}",
// "name": "Null Output",
// "output_id": "{EEEB07DE-C2C8-44C2-985C-C85856D96DA1}"
// },
// {
// "active": true,
// "device_id": "{00000000-0000-0000-0000-000000000000}",
// "name": "Primary Sound Driver",
// "output_id": "{D41D2423-FBB0-4635-B233-7054F79814AB}"
// },
// {
// "active": false,
// "device_id": "{1C4EC038-97DB-48E7-9C9A-05FDED46847B}",
// "name": "Speakers (Sound Blaster Z)",
// "output_id": "{D41D2423-FBB0-4635-B233-7054F79814AB}"
// },
// {
// "active": false,
// "device_id": "{41B86272-3D6C-4A5A-8907-4FE7EBE39E7E}",
// "name": "SPDIF-Out (Sound Blaster Z)",
// "output_id": "{D41D2423-FBB0-4635-B233-7054F79814AB}"
// },
// {
// "active": false,
// "device_id": "{9CDC0FAE-2870-4AFA-8287-E86099D69076}",
// "name": "3 - BenQ BL3200 (AMD High Definition Audio Device)",
// "output_id": "{D41D2423-FBB0-4635-B233-7054F79814AB}"
// }
// ]
// Normally, one item in the array has "active" set to true,
// indicating the currently configured output device.
// If the configured output device is unavailable, the array
// may contain no active item.
GetQueryItems(handle_list, query)
Note: use try/catch to handle invalid queries. An empty handle list will be returned if the query is valid but there are no results.
| Name | Type | Description |
|---|---|---|
handle_list | FbMetadbHandleList | |
query | string |
FbMetadbHandleList — Unsorted results.
Error — If handles is null or the query cannot be parsed or processed.
let a = fb.GetQueryItems(plman.GetPlaylistItems(plman.ActivePlaylist), "rating IS 5");let b = fb.GetQueryItems(fb.GetLibraryItems(), "rating IS 5");
GetSelection()
Gets now playing or selected item according to settings in "File>Preferences>Display>Selection viewers".
GetSelections(flags)
Works like fb.GetSelection, but returns a handle list.
| Name | Type | Description |
|---|---|---|
flags = 0optional | number | 1 - no now playing |
GetSelectionType()
Retrieves what the selection type is.
number — see SelectionType enum
0 - undefined (no item)
1 - active_playlist_selection
2 - caller_active_playlist
3 - playlist_manager
4 - now_playing
5 - keyboard_shortcut_list
6 - media_library_viewer
IsLibraryEnabled()
booleanIsLibraryInitialised()
Returns true if the library has already been initialized by this time
booleanIsMainMenuCommandChecked(command)
Performance note: don't use in on_paint.
| Name | Type | Description |
|---|---|---|
command | string | Path to main menu item |
boolean — true, if the item is checked.
fb.RunMainMenuCommand("Playback/Scrobble Tracks"); // available with foo_scrobble
IsMetadbInMediaLibrary(handle)
| Name | Type | Description |
|---|---|---|
handle | FbMetadbHandle |
booleanError — If handle is null.
let np = fb.GetNowplaying();
console.log(fb.IsMetadbInMediaLibrary(np)); // If false, playing track is not in Media Library.
LoadPlaylist()
Loads playlist from file. Equivalent to File>Load Playlist....
Next()
Pause()
Play()
PlayOrPause()
Prev()
Random()
RegisterMainMenuCommand(id, name, description)
Registers a main menu item that will be displayed under main menu > File > JSplitter > Script commands > {Current panel name}.
Being main menu item means you can bind it to global keyboard shortcuts, standard toolbar buttons, panel stack splitter buttons and etc.
Execution of the correspoding menu item will trigger on_main_menu_dynamic callback.
Note: JSplitter uses a combination of panel name and command id to identify and bind the command. Hence all corresponding binds will fail if the id or the panel name is changed. This also means that collision WILL occur if there are two panels with the same name.
Related methods: fb.UnregisterMainMenuCommand
Related callbacks: on_main_menu_dynamic
| Name | Type | Description |
|---|---|---|
id | number | |
name | string | |
description = ''optional | string |
Error — If the panel host is not fully initialized, the command id is already registered, or the command cannot be registered.
Restart()
RunContextCommand(command, flags)
Shows context menu for currently played track.
| Name | Type | Description |
|---|---|---|
command | string | |
flags = 0optional | number | 0 - default (depends on whether SHIFT key is pressed, flag_view_reduced or flag_view_full is selected) |
booleanfb.RunContextCommand("Properties");
RunContextCommandWithMetadb(command, handle_or_handle_list, flags)
Shows context menu for supplied tracks.
| Name | Type | Description |
|---|---|---|
command | string | |
handle_or_handle_list | FbMetadbHandle|FbMetadbHandleList | Handles on which to apply context menu |
flagsoptional | number | Same flags as fb.RunContextCommand |
booleanError — If handle_or_handle_list is not an FbMetadbHandle or FbMetadbHandleList object.
RunMainMenuCommand(command)
| Name | Type | Description |
|---|---|---|
command | string |
booleanfb.RunMainMenuCommand("File/Add Location...");
SavePlaylist()
SetAudioStream(handle, index)
Selects an audio stream for handle and stores it as the user's stream preference.
Available only in foobar2000 v2.0 and above. Throws an Error when API is unavailable, the file does not support stream selection, or index is out of bounds.
If the file is currently playing and the effective selection changes, playback is restarted so the new stream is applied immediately.
Related methods: fb.GetAudioStreams.
| Name | Type | Description |
|---|---|---|
handle | FbMetadbHandle | |
index | number | Zero-based stream index returned by fb.GetAudioStreams. |
Error — If handle is null, foobar2000 2.0 stream selection is unavailable, the file does not support audio stream selection, or index is out of bounds.
const handle = fb.GetFocusItem();
if (handle) {
const streams = fb.GetAudioStreams(handle);
if (streams.length > 1) {
fb.SetAudioStream(handle, streams[1].index);
}
}
SetDSPPreset(idx)
Available only in foobar2000 v1.4 and above. Throws a script error on v1.3.
Related methods: fb.GetDSPPresets.
| Name | Type | Description |
|---|---|---|
idx | number |
Error — If idx is out of bounds.
let str = fb.GetDSPPresets();
let arr = JSON.parse(str);
let idx; // find the required DSP from `arr` and assign it to `idx`
fb.SetDSPPreset(idx);
SetOutputDevice(output, device)
Available only in foobar2000 v1.4 and above. Throws a script error on v1.3.
Related methods: fb.GetOutputDevices.
| Name | Type | Description |
|---|---|---|
output | string | |
device | string |
// To actually change device, you'll need the device_id and output_id
// and use them with fb.SetOutputDevice.
let str = fb.GetOutputDevices();
let arr = JSON.parse(str);
// Assuming same list from above, switch output to the last device.
fb.SetOutputDevice(arr[4].output_id, arr[4].device_id);
ShowConsole(show)
Shows foobar2000 console window or close it (if show=false).
| Name | Type | Description |
|---|---|---|
show = trueoptional | boolean |
ShowLibrarySearchUI(query)
Opens the Library>Search window populated with the query you set.
| Name | Type | Description |
|---|---|---|
query | string |
ShowPictureViewer(image_path_or_handle, art_id)
Opens the image viewer built in to foobar2000. Pass an image file path, or an FbMetadbHandle; with a handle, AlbumArtId defaults to AlbumArtId.front. Album art is resolved by foobar2000 and may be embedded or external.
Relative filesystem paths are resolved as described in utils.ReadTextFile. This applies to the image-file argument; track handles use foobar2000 artwork lookup.
| Name | Type | Description |
|---|---|---|
image_path_or_handle | (string|FbMetadbHandle) | Image file path or track handle. |
art_id = AlbumArtId.frontoptional | AlbumArtId | Album art type. Used only when the first argument is an FbMetadbHandle. |
Error — If the track handle is invalid, the foobar2000 image viewer API is unavailable, or an image file path cannot be read.
ShowPlaylistSearchUI()
Opens the "Playlist Search" window
ShowPopupMessage(message, title)
| Name | Type | Description |
|---|---|---|
message | string | |
title = 'JSplitter'optional | string |
ShowPreferences()
Stop()
TitleFormat(expression)
Performance note: if you use the same query frequently, try caching FbTitleFormat object (by storing it somewhere), instead of creating it every time.
| Name | Type | Description |
|---|---|---|
expression | string |
UnregisterMainMenuCommand(id, name, description)
Unregisters a main menu item.
Related methods: fb.RegisterMainMenuCommand
| Name | Type | Description |
|---|---|---|
id | number |
Error — If the panel host is not fully initialized or id is not a registered dynamic main-menu command.
VolumeDown()
VolumeMute()
VolumeUp()