Awesome
obs_websocket
This package gives access to all of the methods and events outlined by the obs-websocket 5.1.0 protocol reference through the send
method documented below, but also has helper methods for many of the more popular requests that are made available through the protocol reference.
- Breaking changes from v2.4.3 (obs-websocket v4.9.1 protocol)
- Getting Started
- Supported high-level commands
- Helper methods
- Sending Commands to OBS - low level
- Events
- Closing the websocket
- obs_websocket cli (OBS at the command prompt)
- Interesting Projects
- Contributors
- Contributing
Breaking changes from v2.4.3 (obs-websocket v4.9.1 protocol)
The short answer is that everything has changed. The obs-websocket v5.1.0 protocol is very different from the older v4.9.1 protocol. Any code written for the v4.9.1 protocol needs to be re-written for v5.x
Getting Started
Requirements
- The OBS v27.x or above application needs to be installed on a machine reachable on the local network
- The obs-websocket is included with OBS in current versions.
In your project add the dependency:
dependencies:
...
obs_websocket: ^5.1.0+9
For help getting started with dart, check out these guides.
Usage Example
Import the websocket connection library and the response library.
import 'package:obs_websocket/obs_websocket.dart';
Opening a websocket Connection
The WebSocket protocol, described in the specification RFC 6455 provides a way to exchange data between client and server via a persistent connection. The data can be passed in both directions as “packets”.
Before a websocket connection can be made to a running instance of OBS, you will need to have the obs-websocket plugin installed and configured. The instruction and links to downloaded and install are available on the project Release page.
To open a websocket connection, we need to create new ObsWebSocket using the special protocol ws in the url:
final obsWebSocket =
await ObsWebSocket.connect('ws://[obs-studio host ip]:[port]', password: '[password]');
obs-studio host ip
- is the ip address or host name of the OBS device running obs-websocket protocol v5.0.0 that wou would like to send remote control commands to.
port
is the port number used to connect to the OBS device running obs-websocket protocol v5.0.0
password
- is the password configured for obs-websocket.
These settings are available to change and review through the OBS user interface by clicking Tools, obs-websocket Settings
.
Authenticating to OBS
If a password
is supplied to the connect
method, authentication will occur automatically assuming that it is enabled for OBS.
Sending Commands to OBS
The available commands/requests are documented on the protocol page of the obs-websocket github page. Note that not all commands listed on the protocol page have been implemented in code at this time. For any command not yet implemented, refer to the low-level
method of sending commands, documented below.
final status = await obs.stream.status;
// or this works too
// final status = await obs.stream.getStreamStatus();
if (!status.outputActive) {
await obsWebSocket.stream.start();
}
Supported high-level commands
For any of the items that have an [x] from the list below, a high level helper command is available for that operation, i.e. obsWebSocket.general.version
or obsWebSocket.general.getVersion()
. Otherwise a low-level command can be used to perform the operation, i.e. obsWebSocket.send('GetVersion')
.
Supported Requests
- General Requests -
obsWebSocket.general
- [x] GetVersion - Gets data about the current plugin and RPC version.
- [x] GetStats - Gets statistics about OBS, obs-websocket, and the current session.
- [x] BroadcastCustomEvent - Broadcasts a CustomEvent to all WebSocket clients. Receivers are clients which are identified and subscribed.
- [x] CallVendorRequest - Call a request registered to a vendor.
- [x] obsBrowserEvent - A custom helper method that wraps
CallVendorRequest
, and can be used to send data to the obs-browser plugin. - [x] GetHotkeyList - Gets an array of all hotkey names in OBS
- [x] TriggerHotkeyByName - Triggers a hotkey using its name. See GetHotkeyList
- [x] TriggerHotkeyByKeySequence - Triggers a hotkey using a sequence of keys.
- [x] Sleep - Sleeps for a time duration or number of frames. Only available in request batches with types SERIAL_REALTIME or SERIAL_FRAME.
- Config Requests -
obsWebSocket.config
- [x] GetPersistentData - Gets the value of a "slot" from the selected persistent data realm.
- [x] SetPersistentData - Sets the value of a "slot" from the selected persistent data realm.
- [x] GetSceneCollectionList - Gets an array of all scene collections
- [x] SetCurrentSceneCollection - Switches to a scene collection.
- [x] CreateSceneCollection - Creates a new scene collection, switching to it in the process.
- [x] GetProfileList - Gets an array of all profiles
- [x] SetCurrentProfile - Switches to a profile.
- [x] CreateProfile - Creates a new profile, switching to it in the process
- [x] RemoveProfile - Removes a profile. If the current profile is chosen, it will change to a different profile first.
- [x] GetProfileParameter - Gets a parameter from the current profile's configuration.
- [x] SetProfileParameter - Sets the value of a parameter in the current profile's configuration.
- [x] GetVideoSettings - Gets the current video settings.
- [x] SetVideoSettings - Sets the current video settings.
- [x] GetStreamServiceSettings - Gets the current stream service settings (stream destination).
- [x] SetStreamServiceSettings - Sets the current stream service settings (stream destination).
- [ ] GetRecordDirectory - Gets the current directory that the record output is set to.
- Sources Requests -
obsWebSocket.sources
- [x] GetSourceActive - Gets the active and show state of a source.
- [x] GetSourceScreenshot - Gets a Base64-encoded screenshot of a source.
- [x] SaveSourceScreenshot - Saves a screenshot of a source to the filesystem.
- Scenes Requests -
obsWebSocket.scenes
- [x] GetSceneList - Gets an array of all scenes in OBS.
- [x] GetGroupList - Gets an array of all groups in OBS.
- [x] GetCurrentProgramScene - Gets the current program scene.
- [x] SetCurrentProgramScene - Sets the current program scene.
- [x] GetCurrentPreviewScene - Gets the current preview scene (only available when studio mode is enabled).
- [x] SetCurrentPreviewScene - Sets the current preview scene (only available when studio mode is enabled).
- [x] CreateScene - Creates a new scene in OBS.
- [x] RemoveScene - Removes a scene from OBS.
- [x] SetSceneName - Sets the name of a scene (rename).
- [x] GetSceneSceneTransitionOverride - Gets the scene transition overridden for a scene.
- [x] SetSceneSceneTransitionOverride - Sets the scene transition overridden for a scene.
- Inputs Requests -
obsWebSocket.inputs
- [x] GetInputList
- [x] GetInputKindList
- [ ] GetSpecialInputs
- [ ] CreateInput
- [x] RemoveInput - Removes an existing input.
- [x] SetInputName - Sets the name of an input (rename).
- [ ] GetInputDefaultSettings
- [ ] GetInputSettings
- [ ] SetInputSettings
- [x] GetInputMute - Gets the audio mute state of an input.
- [x] SetInputMute - Sets the audio mute state of an input.
- [x] ToggleInputMute - Toggles the audio mute state of an input.
- [ ] GetInputVolume
- [ ] SetInputVolume
- [ ] GetInputAudioBalance
- [ ] SetInputAudioBalance
- [ ] GetInputAudioSyncOffset
- [ ] SetInputAudioSyncOffset
- [ ] GetInputAudioMonitorType
- [ ] SetInputAudioMonitorType
- [ ] GetInputAudioTracks
- [ ] SetInputAudioTracks
- [ ] GetInputPropertiesListPropertyItems
- [ ] PressInputPropertiesButton
- Transitions Requests -
obsWebSocket.transitions
- [ ] GetTransitionKindList
- [ ] GetSceneTransitionList
- [ ] GetCurrentSceneTransition
- [x] SetCurrentSceneTransition - Sets the current scene transition.
- [x] SetCurrentSceneTransitionDuration - Sets the duration of the current scene transition, if it is not fixed.
- [ ] SetCurrentSceneTransitionSettings
- [ ] GetCurrentSceneTransitionCursor
- [x] TriggerStudioModeTransition - Triggers the current scene transition. Same functionality as the Transition button in studio mode.
- [ ] SetTBarPosition
- Filters Requests -
obsWebSocket.filters
- [ ] GetSourceFilterList
- [ ] GetSourceFilterDefaultSettings
- [ ] CreateSourceFilter
- [x] RemoveSourceFilter - Sets the index position of a filter on a source.
- [x] SetSourceFilterName - Sets the name of a source filter (rename).
- [ ] GetSourceFilter
- [x] SetSourceFilterIndex - Sets the index position of a filter on a source.
- [ ] SetSourceFilterSettings
- [x] SetSourceFilterEnabled - Sets the enable state of a source filter.
- Scene Items Requests -
obsWebSocket.sceneItems
- [x] GetSceneItemList - Gets a list of all scene items in a scene.
- [x] GetGroupSceneItemList - Basically GetSceneItemList, but for groups.
- [x] GetSceneItemId - Searches a scene for a source, and returns its id.
- [ ] CreateSceneItem
- [ ] RemoveSceneItem
- [ ] DuplicateSceneItem
- [ ] GetSceneItemTransform
- [ ] SetSceneItemTransform
- [x] GetSceneItemEnabled - Gets the enable state of a scene item.
- [x] SetSceneItemEnabled - Sets the enable state of a scene item.
- [x] GetSceneItemLocked - Gets the lock state of a scene item.
- [x] SetSceneItemLocked - Sets the lock state of a scene item.
- [x] GetSceneItemIndex - Gets the index position of a scene item in a scene.
- [x] SetSceneItemIndex - Sets the index position of a scene item in a scene.
- [ ] GetSceneItemBlendMode
- [ ] SetSceneItemBlendMode
- Outputs Requests -
obsWebSocket.outputs
- [x] GetVirtualCamStatus - Gets the status of the virtualcam output.
- [x] ToggleVirtualCam - Toggles the state of the virtualcam output.
- [x] StartVirtualCam - Starts the virtualcam output.
- [x] StopVirtualCam - Stops the virtualcam output.
- [x] GetReplayBufferStatus - Gets the status of the replay buffer output.
- [x] ToggleReplayBuffer - Toggles the state of the replay buffer output.
- [x] StartReplayBuffer - Starts the replay buffer output.
- [x] StopReplayBuffer - Stops the replay buffer output.
- [x] SaveReplayBuffer - Saves the contents of the replay buffer output.
- [ ] GetLastReplayBufferReplay
- [ ] GetOutputList
- [ ] GetOutputStatus
- [x] ToggleOutput - Toggles the status of an output.
- [x] StartOutput - Starts an output.
- [x] StopOutput - Stops an output.
- [ ] GetOutputSettings
- [ ] SetOutputSettings
- Stream Requests -
obsWebSocket.stream
- [x] GetStreamStatus - Gets the status of the stream output.
- [x] ToggleStream - Toggles the status of the stream output.
- [x] StartStream - Starts the stream output.
- [x] StopStream - Stops the stream output.
- [x] SendStreamCaption - Sends CEA-608 caption text over the stream output.
- Record Requests -
obsWebSocket.record
- [x] GetRecordStatus - Gets the status of the record output.
- [x] ToggleRecord - Toggles the status of the record output.
- [x] StartRecord - Starts the record output.
- [x] StopRecord - Stops the record output.
- [x] ToggleRecordPause - Toggles pause on the record output.
- [x] PauseRecord - Pauses the record output.
- [x] ResumeRecord - Resumes the record output.
- Media Inputs Requests -
obsWebSocket.mediaInputs
- [ ] GetMediaInputStatus
- [x] SetMediaInputCursor - Sets the cursor position of a media input.
- [x] OffsetMediaInputCursor - Offsets the current cursor position of a media input by the specified value.
- [ ] TriggerMediaInputAction
- Ui Requests -
obsWebSocket.ui
- [x] GetStudioModeEnabled - Gets whether studio is enabled.
- [x] SetStudioModeEnabled - Enables or disables studio mode.
- [x] OpenInputPropertiesDialog - Opens the properties dialog of an input.
- [x] OpenInputFiltersDialog - Opens the filters dialog of an input.
- [x] OpenInputInteractDialog - Opens the interact dialog of an input.
- [x] GetMonitorList - Gets a list of connected monitors and information about them.
- [x] OpenVideoMixProjector - Opens a projector for a specific output video mix.
- [x] OpenSourceProjector - Opens a projector for a source.
Helper methods
browserEvent
A custom helper method that wraps CallVendorRequest
, and can be used to send data to the obs-browser plugin.
await obsWebSocket.general.obsBrowserEvent(
eventName: 'obs-websocket-test-event',
eventData: {
'my': 'data',
'that': 'will be displayed in an event',
},
);
The Dart
code above will send an event to the obs-browser plugin. By including the Javascript shown below in a page referenced by the plugin, that page can receive and react to events generated by Dart
code.
window.addEventListener('obs-websocket-test-event', function(event) {
console.log(event); // {"my":"data","that":"will be displayed in an event"}
});
Sending Commands to OBS - low level
Alternatively, there is a low-level interface for sending commands. This can be used in place of the above, or in the case that a specific documented Request has not been implemented as a helper method yet. The available commands are documented on the protocol page of the obs-websocket github page
var response = await obsWebSocket.send('GetStreamStatus');
print('request status: ${response?.requestStatus.code}'); // 100 - for success
print('is streaming: ${response?.responseData?['outputActive']}'); // false - if not currently streaming
response?.requestStatus.result
will be true
on success. response?.requestStatus.code
will give a response code that is explained in the RequestStatus portion of the protocol documentation.
response?.requestStatus.comment
will sometimes give additional information about errors that might be generated.
Dealing with a list in the responseData
.
var response = await obs.send('GetSceneList');
var scenes = response?.responseData?['scenes'];
scenes.forEach(
(scene) => print('${scene['sceneName']} - ${scene['sceneIndex']}'));
Additionally you can provide arguments with a command:
response = await obs.send('GetVideoSettings');
var newSettings =
Map<String, dynamic>.from(response?.responseData as Map<String, dynamic>);
newSettings.addAll({
'baseWidth': 1440,
'baseHeight': 1080,
'outputWidth': 1440,
'outputHeight': 1080
});
// send the settings as an additional parameter.
await obs.send('SetVideoSettings', newSettings);
Events
Events generated by OBS through the websocket can be hooked into by supplying an event listener in the form of addHandler<T>(Function handler)
. In the sample code below a hook is created that waits for a SceneItemEnableStateChanged
event. If the specified SceneItem
is visible the code hides the SceneItem
after 13 seconds. This code from the show_scene_item.dart
example could be used in a cron job to show and then hide an OBS SceneItem
periodically.
final obsWebSocket = await ObsWebSocket.connect(config['host'], password: config['password']);
// sceneItem to show/hide
final sceneItem = 'ytBell';
// tell obsWebSocket to listen to events, since the default is to ignore them
await obsWebSocket.listen(EventSubscription.all.code);
// get the current scene
final currentScene = await obsWebSocket.scenes.getCurrentProgramScene();
// get the id of the required sceneItem
final sceneItemId = await obsWebSocket.sceneItems.getSceneItemId(SceneItemId(
sceneName: currentScene,
sourceName: sceneItem,
));
// this handler will only run when a SceneItemEnableStateChanged event is generated
obsWebSocket.addHandler<SceneItemEnableStateChanged>(
(SceneItemEnableStateChanged sceneItemEnableStateChanged) async {
print(
'event: ${sceneItemEnableStateChanged.sceneName} ${sceneItemEnableStateChanged.sceneItemEnabled}');
// make sure we have the correct sceneItem and that it's currently visible
if (sceneItemEnableStateChanged.sceneName == currentScene &&
sceneItemEnableStateChanged.sceneItemEnabled) {
// wait 13 seconds
await Future.delayed(Duration(seconds: 13));
// hide the sceneItem
await obsWebSocket.sceneItems.setSceneItemEnabled(SceneItemEnableStateChanged(
sceneName: currentScene,
sceneItemId: sceneItemId,
sceneItemEnabled: false));
// close the socket when complete
await obsWebSocket.close();
}
});
// get the current state of the sceneItem
final sceneItemEnabled =
await obsWebSocket.sceneItems.getSceneItemEnabled(SceneItemEnabled(
sceneName: currentScene,
sceneItemId: sceneItemId,
));
// if the sceneItem is hidden, show it
if (!sceneItemEnabled) {
await obsWebSocket.sceneItems.setSceneItemEnabled(SceneItemEnableStateChanged(
sceneName: currentScene,
sceneItemId: sceneItemId,
sceneItemEnabled: true));
}
Supported Events for addHandler<T>
- General Events
- [x] ExitStarted - OBS has begun the shutdown process.
- [x] VendorEvent - An event has been emitted from a vendor.
- Config Events
- [x] CurrentSceneCollectionChanging - The current scene collection has begun changing.
- [x] CurrentSceneCollectionChanged - The current scene collection has changed.
- [x] SceneCollectionListChanged - The scene collection list has changed.
- [x] CurrentProfileChanging - The current profile has begun changing.
- [x] CurrentProfileChanged - The current profile has changed.
- [x] ProfileListChanged - The profile list has changed.
- Scenes Events
- [ ] SceneCreated
- [ ] SceneRemoved
- [ ] SceneNameChanged
- [ ] CurrentProgramSceneChanged
- [ ] CurrentPreviewSceneChanged
- [ ] SceneListChanged
- Inputs Events
- [ ] InputCreated
- [ ] InputRemoved
- [ ] InputNameChanged
- [ ] InputActiveStateChanged
- [ ] InputShowStateChanged
- [ ] InputMuteStateChanged
- [ ] InputVolumeChanged
- [ ] InputAudioBalanceChanged
- [ ] InputAudioSyncOffsetChanged
- [ ] InputAudioTracksChanged
- [ ] InputAudioMonitorTypeChanged
- [ ] InputVolumeMeters
- Transitions Events
- Filters Events
- Scene Items Events
- [ ] SceneItemCreated
- [ ] SceneItemRemoved
- [ ] SceneItemListReindexed
- [x] SceneItemEnableStateChanged - A scene item's enable state has changed.
- [ ] SceneItemLockStateChanged
- [x] SceneItemSelected - A scene item has been selected in the Ui.
- [ ] SceneItemTransformChanged
- Outputs Events
- [x] StreamStateChanged - The state of the stream output has changed.
- [x] RecordStateChanged - The state of the record output has changed.
- [ ] ReplayBufferStateChanged
- [ ] VirtualcamStateChanged
- [ ] ReplayBufferSaved
- Media Inputs Events
- Ui Events
- [x] StudioModeStateChanged - Studio mode has been enabled or disabled.
- [x] ScreenshotSaved - A screenshot has been saved.
Handling events not yet supported
You can supply a fallbackEvent
to the ObsWebSocket
constructor to handle events that are not yet supported directly in the code. The following code snippet provides an example of this.
final obs = await ObsWebSocket.connect(
'ws://[obs-studio host ip]:4455',
password: '[password]',
fallbackEventHandler: (Event event) =>
print('type: ${event.eventType} data: ${event.eventData}'),
);
// tell obsWebSocket to listen to events, since the default is to ignore them
await obsWebSocket.listen(EventSubscription.all);
Closing the websocket
Finally before your code completes, you will should close the websocket connection. Failing to close the connection can lead to unexpected performance related issues for your OBS instance.
obsWebSocket.close();
obs_websocket cli (OBS at the command prompt)
A command line interface for controlling an OBS with cli commands
Please see the cli documentation README.md for more detailed usage information.
Install using dart pub
:
dart pub global activate obs_websocket
Install using brew
:
brew tap faithoflifedev/obs_websocket
brew install obs
Run the following command to see help:
obs --help
Result,
A command line interface for controlling OBS.
Usage: obs <command> [arguments]
Global options:
-h, --help Print this usage information.
-u, --uri=<ws://[host]:[port]> The url and port for OBS websocket
-t, --timeout=<int> The timeout in seconds for the web socket connection.
-l, --log-level [all, debug, info, warning, error, off (default)]
-p, --passwd=<string> The OBS websocket password, only required if enabled in OBS
Available commands:
authorize Generate an authentication file for an OBS connection
config Config Requests
general General commands
listen Generate OBS events to stdout
scene-items Scene Items Requests
send Send a low-level websocket request to OBS
sources Commands that manipulate OBS sources
stream Commands that manipulate OBS streams
ui Commands that manipulate the OBS user interface.
version Display the package name and version
Interesting Projects
Using Flutter as a source in OBS - a blog post by Aloïs Deniel were he shows a simple way to use a Fluttter application as a custom source in OBS on macOS. He uses it to create animated scenes on his live streams on Twitch: a custom Flutter widget is used for each scene and is kept in sync with OBS thanks to the OBS websocket protocol.
Contributors
- <img src="https://avatars.githubusercontent.com/u/923202?v=4" width="25" height="25"> faithoflifedev
Contributing
Any help from the open-source community is always welcome and needed:
- Found an issue?
- Please fill a bug report with details.
- Need a feature?
- Open a feature request with use cases.
- Are you using and liking the project?
- Promote the project: create an article or post about it
- Make a donation
- Do you have a project that uses this package
- let's cross promote, let me know and I'll add a link to your project
- Are you a developer?
- Fix a bug and send a pull request.
- Implement a new feature.
- Improve the Unit Tests.
- Have you already helped in any way?
- Many thanks from me, the contributors and everybody that uses this project!
If you donate 1 hour of your time, you can contribute a lot, because others will do the same, just be part and start with your 1 hour.