9369
1
2
OBS Studio Web Socket tutorial with examples Python and Javascript

OBS Studio Web Socket tutorial with examples Python and Javascript

Published on September 18, 2023 by M. Maxim

OBS Studio WebSocket Tutorial with Examples in Python and JavaScript

WebSockets are a powerful communication protocol that allows real-time, bidirectional communication between a client and a server. OBS Studio utilizes WebSockets to expose its internal functions remotely. This capability is immensely useful for automating actions such as changing scenes, updating overlays, triggering transitions, and more.

As of OBS Studio 28 and later, the obs-websocket plugin is built into OBS by default. The plugin follows a versioned protocol (currently 5.x+), and older versions of scripts that use the now-deprecated 4.x protocol will not work without updates.

This guide covers the modern WebSocket usage for OBS Studio using the official client libraries in both Python and JavaScript. We'll walk you through how to connect, authenticate, and perform basic actions like changing scenes or updating source properties.

Prerequisites

  • OBS Studio: Ensure you have version 28 or later.
  • Enable the WebSocket server under OBS settings.
  • Install necessary libraries for your language of choice:
    • Python: pip install obsws-python
    • JavaScript: npm install obs-websocket-js

Setting Up WebSocket Server in OBS Studio

  1. Open OBS Studio.
  2. Navigate to Tools > WebSocket Server Settings.
  3. Ensure the Enable WebSocket Server box is checked.
  4. Set the Server Port (default is 4455 for protocol v5).
  5. Set a secure password (optional but recommended).
  6. Ensure "Enable authentication" is toggled on if you set a password.
  7. Click "Apply" and then "OK".

Note: OBS WebSocket v5 uses JSON-RPC 2.0 over WebSocket and is significantly different from v4.

Connecting to OBS WebSocket using Python

We'll use the official obsws-python client which supports OBS WebSocket 5.x and provides an intuitive API for scripting automation.

Python Example: Change Scene


from obsws_python import obsws, requests

host = "localhost"
port = 4455
password = "your_password"

# Create a connection to OBS
ws = obsws(host, port, password)
ws.connect()

# Change the current scene
scene_name = "YourSceneName"  # Replace with an actual scene
ws.call(requests.SetCurrentProgramScene(scene_name))

# Disconnect when done
ws.disconnect()
    

This example connects to the OBS WebSocket server, authenticates, and switches to a scene called "YourSceneName". You can explore the available methods using the requests module to control everything from transitions to media playback.

Connecting to OBS WebSocket using JavaScript

For JavaScript, the most robust and modern solution is the obs-websocket-js library, which supports all WebSocket v5 features.

JavaScript Example: Change Scene


import OBSWebSocket from 'obs-websocket-js';

const obs = new OBSWebSocket();

async function changeScene() {
    try {
        await obs.connect('ws://localhost:4455', 'your_password');

        // Change the current program scene
        await obs.call('SetCurrentProgramScene', {
            sceneName: 'YourSceneName'
        });

        console.log('Scene changed successfully!');
        await obs.disconnect();
    } catch (error) {
        console.error('OBS WebSocket Error:', error);
    }
}

changeScene();
    

Ensure you're running this in an environment that supports modules or use bundlers like Webpack/Vite. This code authenticates and changes the current scene programmatically. The library also provides detailed type support and method documentation.

Handling Events and Listening for Changes

OBS WebSocket also allows clients to subscribe to events, enabling reactive programming. You can listen for scene changes, transitions, streaming status, and more.

JavaScript Event Listening Example


obs.on('CurrentProgramSceneChanged', data => {
    console.log(`Scene changed to: ${data.sceneName}`);
});

obs.on('StreamStateChanged', state => {
    console.log(`Streaming: ${state.outputActive}`);
});
    

This lets you build responsive dashboards or bots that react to what's happening in OBS in real time.

Advanced Use Cases

Toggle a Source Visibility

Python:


ws.call(requests.SetSceneItemEnabled(
    scene_name="YourSceneName",
    scene_item_id=3,  # You need to get this ID first
    scene_item_enabled=True
))
    

JavaScript:


await obs.call('SetSceneItemEnabled', {
    sceneName: 'YourSceneName',
    sceneItemId: 3,
    sceneItemEnabled: true
});
    

Get a List of Scenes


const scenes = await obs.call('GetSceneList');
console.log(scenes);
    

This allows you to dynamically generate UI components or log the current OBS configuration.

Security Considerations

  • Always use a password and disable external access unless necessary.
  • If exposing to the internet, use WebSocket proxies (like Nginx) and SSL (WSS://) connections.
  • Limit IP access through firewalls or OBS settings.

OBS WebSocket Documentation

To take full advantage of OBS Studio's WebSocket interface, it's essential to familiarize yourself with the official protocol documentation. The OBS WebSocket 5.x protocol introduces structured request-response methods and standardized event subscriptions.

Here are some vital resources:

These resources are actively maintained and offer example code, API definitions, and release notes that help you stay current with updates and new features.

Common Errors and Troubleshooting

While using OBS WebSocket, you might encounter some common errors. Here’s a guide to resolving typical issues:

  • Connection Refused: Ensure the WebSocket server is enabled in OBS under Tools > WebSocket Server Settings. Also, check if your firewall or antivirus is blocking port 4455.
  • Authentication Failed: Double-check that the password in your client script matches the one set in OBS Studio.
  • Invalid Request Type: Make sure you’re using valid method names from the 5.x protocol. OBS WebSocket 4.x methods like "SetCurrentScene" are now "SetCurrentProgramScene" in 5.x.
  • Scene or Source Not Found: Scene names are case-sensitive. Use the `GetSceneList` or `GetInputList` calls to verify available names and IDs.
  • OBS Crashes on Connect: If this happens, update OBS Studio and the client library. Also, test your setup using the official test clients.

Security Considerations

OBS WebSocket allows powerful remote control over your OBS instance. As such, security is crucial to prevent unauthorized access or disruptions.

  • Use Strong Passwords: Always set a strong WebSocket server password in OBS Studio settings.
  • Local Access Only: Avoid exposing OBS WebSocket to the public internet unless absolutely necessary. Keep your OBS setup behind a firewall or VPN.
  • Use WSS (WebSocket Secure): If deploying over a network, consider using a reverse proxy (like NGINX) to wrap WebSocket traffic in TLS encryption.
  • Audit Scripts: Only run automation scripts from trusted sources. OBS WebSocket can perform destructive operations (e.g., stopping the stream, closing scenes).
  • Keep OBS and Plugins Updated: Updates often include security patches and protocol enhancements.

Real-World Applications

With the OBS WebSocket API, you can integrate OBS into many creative and professional workflows. Here are a few real-world use cases:

  • Streaming Bots: Integrate with Twitch or YouTube bots that can trigger scene switches, camera zooms, or overlays when chat commands are used.
  • Game Integrations: Automatically update scenes or overlays based on game events using third-party APIs or log parsers.
  • Remote Control Dashboards: Build custom control panels (web or desktop-based) to manage OBS Studio remotely, ideal for teams or dual-PC setups.
  • Automated Production: Schedule scene changes, ad breaks, or alerts using cron jobs or OBS macros powered by WebSocket commands.
  • IoT Streaming Integration: Combine OBS with physical sensors (e.g., stream deck buttons, RFID) to trigger visual changes or alerts on stream.

Conclusion

OBS Studio WebSocket 5.x protocol brings powerful, structured control capabilities to content creators, developers, and automation enthusiasts. With support for modern programming languages and well-documented libraries like obs-websocket-js and obsws-python, integrating OBS into your applications is now easier and more secure.

This tutorial showed you how to connect to OBS Studio’s WebSocket server, authenticate securely, send basic commands like changing scenes, and listen for events in both Python and JavaScript. You also learned how to handle errors, protect your setup, and apply this knowledge in real-world scenarios.

If you're serious about stream automation or building custom broadcasting tools, continue exploring the protocol reference and contributing to the OBS community. The possibilities are only limited by your creativity.

Further Resources:

Comments (2)
BU
Buckrats April 2, 2024 16:08

Hi - I have tried both the python and javascript versions. I have changed the scene name to match one of my scenes. Both connect to OBS OK, and disconnect cleanly at the end. But the scene does not change, and looking in the OBS log I see 17:01:13.601: [obs-websocket 4.9.1-compat] Response

M.
M. Maxim April 3, 2024 13:06

I'll have to update this article because in the latest versions of OBS it seems they have changed the keys for changing the scene, I'm currently having issues myself with the .NET part I want to integrate in this tutorial... Will update as soon as I figure out what's going on with the websocket plugin.

Leave a Comment
Replying to someone's comment. Cancel
9369
1
2
Join Our OBS Community

Loading...

Join Now