obs-websocket-js

repository·master·Indexed 20 days ago

https://github.com/obs-websocket-community-projects/obs-websocket-js

A JavaScript library for connecting to the OBS WebSocket plugin, allowing developers to control OBS Studio programmatically. It supports both JSON and Msgpack encodings, provides TypeScript definitions for events and requests, and includes methods for establishing connections, sending single or batch requests via call() and callBatch(), and listening for OBS events.

Tokens
3.8K
Snippets
19
Records
20
Agent score
73%

What's inside obs-websocket-js

  1. Choose between JSON and Msgpack builds

    master

    The dist folder contains two different builds to support different message encodings. Choosing the right one depends on your environment and requirements.

    EncodingUsageBenefitsDownsides
    JSONDefault / Manual opt-in (import OBSWebSocket from 'obs-web-socket/json')Easier debugging, smaller bundleHigher bandwidth usage
    MsgpackWeb bundles / Node.js (import OBSWebSocket from 'obs-web-socket/msgpack')Lower bandwidth usageHarder to debug, larger bundle size

    Note: Modern bundlers will automatically opt into modern builds using modern JS features. If you need to support older browsers, ensure your bundler (e.g., via Babel) transpiles the dependencies.

  2. Install obs-websocket-js

    master

    You can install obs-websocket-js via a package manager for Node.js environments or use a CDN build for browser-based applications.

    Via package manager

    Recommended for Node.js, web apps using bundlers (webpack, rollup), or when you need TypeScript definitions.

    npm install obs-websocket-js
    yarn add obs-websocket-js

    Standalone file / CDN build

    Available via jsdeliver or unpkg:

    • https://cdn.jsdelivr.net/npm/obs-websocket-js
    • https://unpkg.com/obs-websocket-js
    npm install obs-websocket-js
  3. Enable debug logging

    master

    To enable debug logging for obs-websocket-js, use the DEBUG environment variable. You can target all modules using the obs-websocket-js:* pattern.

    Node.js / CLI

    Set the DEBUG environment variable before running your application.

    Browser

    In a browser environment, set the debug key in localStorage.

    If you are using multiple libraries that support the debug package, you can combine them using commas.

    # Enables debug logging for all modules of obs-websocket-js
    DEBUG=obs-websocket-js:*
    
    # on Windows
    set DEBUG=obs-websocket-js:*
    // Browser debugging
    localStorage.debug = 'obs-websocket-js:*';
    
    // Combining with other libraries
    localStorage.debug = 'foo,bar:*,obs-websocket-js:*';
  4. Listen to OBS WebSocket events

    master

    The client is an EventEmitter that emits several key connection-related events. You can subscribe to these to handle the lifecycle of your connection.

    Key Events:

    • ConnectionOpened: Emitted when the WebSocket connection is established.
    • ConnectionClosed: Emitted when the connection is closed. Carries an OBSWebSocketError.
    • ConnectionError: Emitted when a connection error occurs. Carries an OBSWebSocketError.
    • Hello: Emitted when the Hello message is received.
    • Identified: Emitted when the Identified message is received.
    • Custom Events: Any event sent by OBS (e.g., SceneItemList) is emitted by the client using the eventType provided in the message.
    client.on('Identified', (data) => {
      console.log('Identified with data:', data);
    });
    
    client.on('SceneList', (data) => {
      console.log('Scene list changed:', data);
    });
  5. Use TypeScript with obs-websocket-js

    master

    The library is written in TypeScript and includes published type definitions that match the current version of obs-websocket. You can use the following named exports to enforce strict typing for events, requests, and responses:

    • OBSEventTypes: For typing event payloads.
    • OBSRequestTypes: For typing request parameters.
    • OBSResponseTypes: For typing response payloads.

    While function parameters often enforce typings automatically, these exports are useful for explicit type annotations in event handlers and request objects.

    import OBSWebSocket, {OBSEventTypes, OBSRequestTypes, OBSResponseTypes} from 'obs-websocket-js';
    
    function onProfileChanged(event: OBSEventTypes['CurrentProfileChanged']) {
      event.profileName
    }
    
    obs.on('CurrentProfileChanged', onProfileChanged);
    
    const req: OBSRequestTypes['SetSceneName'] = {
      sceneName: 'old-and-busted',
      newSceneName: 'new-hotness'
    };
    obs.call('SetSceneName', req);
  6. Listen for OBS events

    master

    Use the standard event emitter API to listen for events emitted by the OBS Websocket server.

    Methods:

    • on(event, handler): Register a listener.
    • once(event, handler): Register a listener that triggers once.
    • off(event, handler): Remove a listener.
    • addListener(event, handler): Alias for on.
    • removeListener(event, handler): Alias for off.

    Example:

    function onCurrentSceneChanged(event) {
      console.log('Current scene changed to', event.sceneName);
    }
    
    obs.on('CurrentSceneChanged', onCurrentSceneChanged);
    
    // Using once
    obs.once('ExitStarted', () => {
      console.log('OBS started shutdown');
    });

    Internal Client Events

    The client also emits these internal events:

    • ConnectionOpened: Connection opened (no data).
    • ConnectionClosed: Connection closed (returns OBSWebSocketError).
    • ConnectionError: Connection closed due to an error.
    • Hello: Server sent Hello message (returns Hello data).
    • Identified: Client connected and identified (returns Identified data).
    obs.on('CurrentSceneChanged', (event) => {
      console.log('Current scene changed to', event.sceneName);
    });
  7. Send requests with call()

    master

    Send individual requests to OBS using the call method. It returns a Promise that resolves with the response data or rejects with an error from OBS.

    Signature: call(requestType: string, requestData?: object): Promise

    Example:

    // Request without data
    const { currentProgramSceneName } = await obs.call('GetCurrentProgramScene');
    
    // Request with data
    await obs.call('SetCurrentProgramScene', { sceneName: 'Gameplay' });
    
    // Toggle input mute
    const { inputMuted } = await obs.call('ToggleInputMute', { inputName: 'Camera' });
    const {currentProgramSceneName} = await obs.call('GetCurrentProgramScene');
    await obs.call('SetCurrentProgramScene', {sceneName: 'Gameplay'});
  8. Create an OBSWebSocket client

    master

    To use the library, instantiate the OBSWebSocket class. The import method depends on your module system.

    ES Modules (Recommended):

    import { OBSWebSocket } from 'obs-websocket-js';
    const obs = new OBSWebSocket();

    CommonJS (require):

    const { OBSWebSocket } = require('obs-websocket-js');
    // OR
    const OBSWebSocket = require('obs-web-socket-js').OBSWebSocket;
    
    const obs = new OBSWebSocket();
  9. Send batch requests with callBatch()

    master

    Execute multiple requests in a single message to improve efficiency. The server executes the requests based on provided options and returns a list of results once all are finished.

    Signature: callBatch(requests: RequestBatchRequest[], options?: RequestBatchOptions): Promise<ResponseMessage[]>

    Parameters:

    • requests: An array of request objects (same structure as call).
    • options (optional):
      • executionType: Mode of execution.
      • haltOnFailure (boolean): If true, stops the batch if one request fails.

    Note on Types: obs-websocket-js does not automatically infer response types for batch results. You must cast the responseData to the appropriate type manually.

    Example:

    const results = await obs.callBatch([
      { requestType: 'GetVersion' },
      { requestType: 'SetCurrentPreviewScene', requestData: { sceneName: 'Scene 5' } }
    ]);
    
    // Manual type casting for safety
    const version = (results[0].responseData as OBSResponseTypes['GetVersion']).obsVersion;
    const results = await obs.callBatch([
      { requestType: 'GetVersion' },
      { requestType: 'SetCurrentPreviewScene', requestData: { sceneName: 'Scene 5' } }
    ]);
  10. Connect to an OBS Websocket server

    master

    Use the connect method to establish a connection. It returns a Promise that resolves with data from the Hello and Identified messages, or rejects with a connection error.

    Signature: connect(url?: string, password?: string, identificationParams?: object): Promise

    Parameters:

    • url (string, optional): The Websocket URL (e.g., ws://127.0.0.1:4455 or wss://... for secure connections).
    • password (string, optional): Authentication password.
    • identificationParams (object, optional): Parameters for the Identify message, such as rpcVersion to ensure compatibility.

    Example:

    try {
      const { obsWebSocketVersion, negotiatedRpcVersion } = await obs.connect('ws://192.168.0.4:4455', 'password', {
        rpcVersion: 1
      });
      console.log(`Connected to server ${obsWebSocketVersion} (using RPC ${negotiatedRpcVersion})`);
    } catch (error) {
      console.error('Failed to connect', error.code, error.message);
    }
    import OBSWebSocket, {EventSubscription} from 'obs-websocket-js';
    const obs = new OBSWebSocket();
    
    await obs.connect('ws://127.0.0.1:4455', 'super-sekret', { rpcVersion: 1 });