### Install obs-websocket-js via npm or yarn Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/README.md Use npm or yarn to install the library for Node.js projects or web applications that use bundlers. ```sh npm install obs-websocket-js ``` ```sh yarn add obs-websocket-js ``` -------------------------------- ### Event Handling Setup Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/samples/web-tester/dist/tester.html Sets up event listeners for a component, merging parent listeners with component-specific handlers. Used during component initialization and updates. ```javascript function et(e,n,r,i,o){var a,s,c,u,l=[],f=!1;for(a in e)s=e[a],c=n[a],(u=fo(a)).plain||(f=!0),t(s)||(t(c)?(t(s.fns)&&(s=e[a]=X(s)),u.handler=s,l.push(u)):s!==c&&(c.fns=s,e[a]=c));if(l.length){f&&l.sort(tt);for(var p=0;p OBS Controller
Disconnected
``` -------------------------------- ### Use Plugin Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/samples/web-tester/dist/tester.html Registers a Vue plugin. Ensures a plugin is not installed multiple times. ```javascript function Ce(t){t.use=function(t){var e=this._installedPlugins||(this._installedPlugins=[]);if(e.indexOf(t)>-1)return this;var n=m(arguments,1);return n.unshift(this),"function"==typeof t.install?t.install.apply(t,n):"function"==typeof t&&t.apply(null,n),e.push(t),this}} ``` -------------------------------- ### Vue Filter Installation Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/samples/web-tester/dist/tester.html Provides a function to install custom Vue filters. It checks for duplicate filter names to prevent conflicts and registers the filters with Vue. ```javascript function e(n){e.each(u,function(t,r){n.filter(r)?console.warn("\n[filter duplication] : A filter named "+r+"has already been installed."): n.filter(r,t)})} var u=r(2),i=r(0); "undefined"!=typeof window&&window.Vue&&Vue.use(e) n.exports=e ``` -------------------------------- ### Get Component Options Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/samples/web-tester/dist/tester.html Retrieves and merges component options, including those from the superclass and extended options. ```javascript function ge(t){var e=t.options;if(t.super){var n=ge(t.super);if(n!==t.superOptions){t.superOptions=n;var r=_e(t);r&&y(t.extendOptions,r),(e=t.options=z(n,t.extendOptions)).name&&(e.components[e.name]=t)}}return e} ``` -------------------------------- ### Buffer Slice Method Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/samples/web-tester/dist/tester.html Creates a new buffer that references the same memory as the original buffer but with different start and end points. Changes to the new buffer may affect the original. ```javascript l.prototype.slice=function(e,t){var n=this.length;e=~~e,t=t===void 0?n:~~t,0>e?(e+=n,0>e&&(e=0)):e>n&&(e=n),0>t?(t+=n,0>t&&(t=0)):t>n&&(t=n),t",(e=e.firstChild)&&e.setAttribute("data-server-rendered","true"),o(r.staticClass)&&(e.setAttribute("class",r.staticClass)),o(r.class)&&e.setAttribute("class",r.class(e)),o(r.style)&&e.setAttribute("style",r.style(e)),o(r.attrs)&&Object.keys(r.attrs).forEach(function(t){e.setAttribute(t,r.attrs[t])}),o(r.props)&&Object.keys(r.props).forEach(function(t){e[t]=r.props[t]}),o(r.domProps)&&Object.keys(r.domProps).forEach(function(t){e[t]=r.domProps[t]}),o(r.events)&&Object.keys(r.events).forEach(function(t){e.addEventListener(t,r.events[t])}),o(r.nativeEvents)&&Object.keys(r.nativeEvents).forEach(function(t){e.addEventListener(t,r.nativeEvents[t])}),i){for(var a=0;a ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import OBSWebSocket, { EventSubscription } from 'obs-websocket-js'; const obs = new OBSWebSocket(); // Basic connection (no password) const info = await obs.connect('ws://127.0.0.1:4455'); console.log(`OBS WebSocket version: ${info.obsWebSocketVersion}`); // Connection with password const info2 = await obs.connect('ws://127.0.0.1:4455', 'my-secret-password'); // Connection with custom event subscriptions const info3 = await obs.connect( 'ws://127.0.0.1:4455', 'my-secret-password', { rpcVersion: 1, eventSubscriptions: EventSubscription.Scenes | EventSubscription.Inputs | EventSubscription.InputVolumeMeters, } ); // Full error handling example try { const { obsWebSocketVersion, negotiatedRpcVersion } = await obs.connect( 'ws://192.168.1.100:4455', 'password', { rpcVersion: 1 } ); console.log(`Connected to OBS ${obsWebSocketVersion} (RPC ${negotiatedRpcVersion})`); } catch (error) { if (error instanceof OBSWebSocketError) { console.error(`Connection failed [${error.code}]: ${error.message}`); } } ``` ### Response #### Success Response (200) - **obsWebSocketVersion** (string) - The version of obs-websocket. - **negotiatedRpcVersion** (number) - The negotiated RPC version. #### Response Example ```json { "obsWebSocketVersion": "5.3.0", "negotiatedRpcVersion": 1 } ``` ### Error Handling - **OBSWebSocketError** - Thrown on connection failure. Contains `code` and `message` properties. - `4008`: Authentication failed. - `4010`: Only one identify allowed. - `-1`: Non-OBS server or invalid subprotocol. ``` -------------------------------- ### Get Element Static and Inline Styles Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/samples/web-tester/dist/tester.html Retrieves static and inline styles from an element and its ancestors, merging them into a single style object. ```javascript function Ln(t,e){var n,r={};if(e)for(var i=t;i.componentInstance;)(i=i.componentInstance._vnode).data&&(n=En(i.data))&&y(r,n);(n=En(t.data))&&y(r,n);for(var o=t;o=o.parent;)o.data&&(n=En(o.data))&&y(r,n);return r} ``` -------------------------------- ### Initialize Component Instance Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/samples/web-tester/dist/tester.html Initializes a component instance with its properties, listeners, and render children. Handles inline templates. ```javascript function _init(t,e){t.prototype._init=function(t){var e=this, n=t&&t.propsData;this.isVueInstance=!0,e._update=function(t,n){e._vnode=t,n&&e._update(n)},e.$options=ye(e,t,e),e._render=function(){var t=e.$options.render,n=e.$createElement;return e._vnode=t(n,e,e.data,e.computed,e.methods),e._vnode.parent=null,e._vnode},me(e),t&&t.el&&e.$mount(t.el),e.$vnode=null,e._isMounted=!1,e._isDestroyed=!1,e._isBeingDestroyed=!1},Object.defineProperties(t.prototype,{$data:{get:function(){return this._data}},$props:{get:function(){return this._props}},$attrs:{get:function(){return this._attrs}},$listeners:{get:function(){return this._listeners}},$parent:{get:function(){return this._parent}},$root:{get:function(){return this._root}},$children:{get:function(){return this._children}},$slots:{get:function(){return this._slots}},$scopedSlots:{get:function(){return Ei||(this._scopedSlots={}),this._scopedSlots}},$refs:{get:function(){return this._refs}},$isServer:{get:function(){return!1}},$vue:{get:function(){return!0}}}}} ``` -------------------------------- ### Component Mount Lifecycle Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/samples/web-tester/dist/tester.html Handles the mounting process of a component, including calling beforeMount and mounted hooks, and setting up the initial watcher for rendering. ```javascript function Ct(t,e,n){t.$el=e,t.$options.render||(t.$options.render=lo),Ot(t,"beforeMount");var r;return r=function(){t._update(t._render(),n)},t._watcher=new $o(t,r,_),n=!1,null==t.$vnode&&(t._isMounted=!0,Ot(t,"mounted")),t} ``` -------------------------------- ### Connect to OBS WebSocket Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/samples/web-tester/dist/tester.html Establishes a connection to the OBS WebSocket server. Handles connection, authentication, and emits events for connection status. Requires an address and optionally a password. ```javascript async connect(e={},t){e=e||{};const n=e.address||'localhost:4444';return this._connected&&this._socket.close(),new Promise(async(t,o)=>{try{await this._connect(n),await this._authenticate(e.password),t()}catch(e){this._socket.close(),this._connected=!1,l(a,'Connection failed:',e),o(e)}}).callback(t)} ``` -------------------------------- ### Sort Listeners by Plainness Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/samples/web-tester/dist/tester.html Sorts event listeners based on whether they are 'plain' (likely referring to non-capturing listeners). Used in event handling setup. ```javascript function tt(t,e){return t.plain?-1:e.plain?1:0} ``` -------------------------------- ### Vue Devtools Initialization Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/samples/web-tester/dist/tester.html Initializing Vue devtools integration. ```javascript setTimeout(function(){Si.devtools&&Wi&&Wi.emit("init",$e)},0) ``` -------------------------------- ### Get Utility Function Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/samples/web-tester/dist/tester.html Retrieves a value from a nested object structure using a path. If the path does not exist, it returns undefined. This is a safe way to access potentially missing properties. ```javascript function e(n,t){return u.get(n,t)} var u=r(1); n.exports=e ``` -------------------------------- ### Connect to OBS WebSocket Server Source: https://context7.com/obs-websocket-community-projects/obs-websocket-js/llms.txt Establishes a WebSocket connection, performs the handshake, and optionally authenticates. Returns a promise with connection info. Handles clean disconnection if already connected. Includes full error handling for connection failures. ```typescript import OBSWebSocket, { EventSubscription } from 'obs-websocket-js'; const obs = new OBSWebSocket(); // Basic connection (no password) const info = await obs.connect('ws://127.0.0.1:4455'); console.log(`OBS WebSocket version: ${info.obsWebSocketVersion}`); // => "OBS WebSocket version: 5.3.0" console.log(`Negotiated RPC version: ${info.negotiatedRpcVersion}`); // => "Negotiated RPC version: 1" // Connection with password const info2 = await obs.connect('ws://127.0.0.1:4455', 'my-secret-password'); // Connection with custom event subscriptions // Only subscribe to scene and input events; explicitly add high-volume volume meters const info3 = await obs.connect( 'ws://127.0.0.1:4455', 'my-secret-password', { rpcVersion: 1, eventSubscriptions: EventSubscription.Scenes | EventSubscription.Inputs | EventSubscription.InputVolumeMeters, } ); // Full error handling example try { const { obsWebSocketVersion, negotiatedRpcVersion } = await obs.connect( 'ws://192.168.1.100:4455', 'password', { rpcVersion: 1 } ); console.log(`Connected to OBS ${obsWebSocketVersion} (RPC ${negotiatedRpcVersion})`); } catch (error) { // error is OBSWebSocketError with .code and .message if (error instanceof OBSWebSocketError) { console.error(`Connection failed [${error.code}]: ${error.message}`); // Close codes: 4008 = auth failed, 4010 = only one identify allowed // code -1 = non-OBS server or invalid subprotocol } } ``` -------------------------------- ### Connect to OBS WebSocket Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/README.md Use the `connect` method to establish a WebSocket connection to the OBS server. It accepts the server URL, an optional password for authentication, and identification parameters like RPC version and event subscriptions. The method returns a promise that resolves with connection details or rejects on error. ```typescript connect(url = 'ws://127.0.0.1:4455', password?: string, identificationParams = {}): Promise ``` ```typescript import OBSWebSocket, {EventSubscription} from 'obs-websocket-js'; const obs = new OBSWebSocket(); // connect to obs-websocket running on localhost with same port await obs.connect(); // Connect to obs-ws running on 192.168.0.4 await obs.connect('ws://192.168.0.4:4455'); // Connect to localhost with password await obs.connect('ws://127.0.0.1:4455', 'super-sekret'); // Connect expecting RPC version 1 await obs.connect('ws://127.0.0.1:4455', undefined, {rpcVersion: 1}); // Connect with request for high-volume event await obs.connect('ws://127.0.0.1:4455', undefined, { eventSubscriptions: EventSubscription.All | EventSubscription.InputVolumeMeters, rpcVersion: 1 }); // A complete 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); } ``` -------------------------------- ### Batch Request Execution with `callBatch()` Source: https://context7.com/obs-websocket-community-projects/obs-websocket-js/llms.txt Demonstrates how to execute multiple OBS WebSocket requests in a batch using `callBatch()`. It showcases different execution types: `SerialRealtime` for sequential execution with minimal delay, `SerialFrame` for sequential execution synchronized with OBS frames, and `Parallel` for concurrent execution of requests. ```APIDOC ## `callBatch()` - Execute Multiple Requests ### Description Executes a list of requests in a batch. The `executionType` parameter controls how these requests are processed. ### Parameters #### `requests` (Array) - Required An array of request objects, where each object has a `requestType` and optional `requestData`. #### `options` (object) - Optional An object containing options for batch execution. ##### `executionType` (RequestBatchExecutionType) - Optional Controls how the batch is executed. Defaults to `SerialRealtime`. - `SerialRealtime`: Requests are executed sequentially as fast as possible. Use `Sleep` request with `sleepMillis` to add delay. - `SerialFrame`: Requests are executed sequentially, one per graphics frame tick. Use `Sleep` request with `sleepFrames` to wait N frames. - `Parallel`: All requests are dispatched concurrently via a thread pool. Best for requests with heavy processing. ### Request Example (SerialRealtime) ```typescript await obs.callBatch([ { requestType: 'StartRecord' }, { requestType: 'Sleep', requestData: { sleepMillis: 5000 } }, { requestType: 'StopRecord' }, ], { executionType: RequestBatchExecutionType.SerialRealtime }); ``` ### Request Example (SerialFrame) ```typescript await obs.callBatch([ { requestType: 'SetSceneItemIndex', requestData: { sceneName: 'Main', sceneItemId: 1, sceneItemIndex: 0 } }, { requestType: 'Sleep', requestData: { sleepFrames: 2 } }, { requestType: 'SetSceneItemIndex', requestData: { sceneName: 'Main', sceneItemId: 1, sceneItemIndex: 3 } }, ], { executionType: RequestBatchExecutionType.SerialFrame }); ``` ### Request Example (Parallel) ```typescript await obs.callBatch([ { requestType: 'GetSourceScreenshot', requestData: { sourceName: 'Cam1', imageFormat: 'jpeg' } }, { requestType: 'GetSourceScreenshot', requestData: { sourceName: 'Cam2', imageFormat: 'jpeg' } }, { requestType: 'GetSourceScreenshot', requestData: { sourceName: 'Cam3', imageFormat: 'jpeg' } }, ], { executionType: RequestBatchExecutionType.Parallel }); ``` ``` -------------------------------- ### SHA-256 Core Implementation Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/samples/web-tester/dist/tester.html The core logic for the SHA-256 hashing algorithm, including initialization and update steps. ```javascript function o(){this.init(),this._w=f,d.call(this,64,56)}function r(e,t,n){return n^e&(t^n)}function s(e,t,n){return e&t|n&(e|t)}function i(e){return(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10)}function l(e){return(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7)}function a(e){return(e>>>7|e<<25)^(e>>>18|e<<14)^e>>>3}function u(e){return(e>>>17|e<<15)^(e>>>19|e<<13)^e>>>10}var p=n(11),d=n(12),c=n(13).Buffer,[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],f=Array(64);p(o,d),o.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},o.prototype._update=function(t){for(var n=this._w,o=0|this._a,p=0|this._b,c=0|this._c,d=0|this._d,e=0|this._e,f=0|this._f,g=0|this._g,h=0|this._h,m=0;16>m;++m)n[m]=t.readInt32BE(4*m);for(;64>m;++m)n ``` -------------------------------- ### Buffer Implementation Details Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/samples/web-tester/dist/tester.html Contains the core implementation for the Buffer class, handling typed array support, various ways of creating and initializing buffers, and encoding/decoding. ```javascript 'use strict'; var o=Math.floor,r=Math.pow,s=Math.min; (function(e){function i(){return l.TYPED_ARRAY_SUPPORT?2147483647:1073741823} function a(e,t){if(i()e)throw new RangeError(' ``` ```javascript size ``` ```javascript " argument must not be negative')} function d(e,t,n,o){return p(t),0>=t?a(e,t):void 0===n?a(e,t):'string'==typeof o?a(e,t).fill(n,o):a(e,t).fill(n)} function c(e,t){if(p(t),e=a(e,0>t?0:0|_(t)),!l.TYPED_ARRAY_SUPPORT)for(var n=0;nt.length?0:0|_(t.length);return(e=a(e,n),0===e.length)?e:(t.copy(e,0,0,n),e)} function m(e,t,n,o){if(t.byteLength,0>n||t.byteLength { if (vendorName !== 'fancy-plugin') { return; } }); const req: OBSRequestTypes['SetSceneName'] = { sceneName: 'old-and-busted', newSceneName: 'new-hotness' }; obs.call('SetSceneName', req); obs.call('SetInputMute', { inputName: 'loud noises', inputMuted: true }); ``` -------------------------------- ### Vue Transition Component Configuration Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/samples/web-tester/dist/tester.html Configuration for Vue's Transition component, including props and render function. ```javascript var Fa={Transition:Da,TransitionGroup:{props:Pa,render:function(t){for(var e=this.tag||this.$vnode.data.tag||"span",n=Object.create(null),r=this.prevChildren=this.children,i=this.$slots.default||\[\] ,o=this.children=\[\] ,a=ir(this),s=0;s-1?ta\[t\]=e.constructor===window.HTMLUnknownElement||e.constructor===window.HTMLElement:ta\[t\]=/HTMLUnknownElement/.test(e.toString())} ``` -------------------------------- ### Handle Model Binding Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/samples/web-tester/dist/tester.html Sets up two-way data binding for components using the 'model' option. ```javascript function ne(t,n){var r=t.model&&t.model.prop||"value",i=t.model&&t.model.event||"input";(n.props||(n.props=!(n.props={})))\[r\]=n.model.value;var o=n.on||(n.on={});e(o\[i\])?o\[i\]=\[n.model.callback\].concat(o\[i\]):o\[i\]=n.model.callback} ``` -------------------------------- ### Vue Component Instantiation Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/samples/web-tester/dist/tester.html Creates a Vue component instance, handling inline templates and data. ```javascript function ui(t,e,n){var r=e.inlineTemplate?null:ni(e,n,!0);return"\_c("+t+"."+Zr(e,n)+(r?"."+r:"")+")"} ``` -------------------------------- ### Execute Transition Sequence with SerialRealtime and Delays Source: https://context7.com/obs-websocket-community-projects/obs-websocket-js/llms.txt Perform a sequence of actions, including scene changes and transitions, with real-time serial execution and a specified delay. `haltOnFailure` can stop the batch if any request fails. ```typescript const results = await obs.callBatch( [ { requestType: 'SetCurrentPreviewScene', requestData: { sceneName: 'Scene 5' } }, { requestType: 'SetCurrentSceneTransition', requestData: { transitionName: 'Fade' } }, { requestType: 'Sleep', requestData: { sleepMillis: 300 } }, { requestType: 'TriggerStudioModeTransition' }, ], { executionType: RequestBatchExecutionType.SerialRealtime, haltOnFailure: true, } ); console.log('All succeeded:', results.every(r => r.requestStatus.result)); ``` -------------------------------- ### Enable Debug Logging (Browser) Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/README.md Configure browser debugging by setting the `localStorage.debug` property. This allows for debugging specific modules or multiple modules simultaneously. ```javascript localStorage.debug = 'obs-websocket-js:*'; ``` ```javascript localStorage.debug = 'foo,bar:*,obs-websocket-js:*'; ``` -------------------------------- ### Import OBSWebSocket for JSON encoding Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/README.md Import the JSON-specific build of OBSWebSocket when you need easier debugging or a smaller bundle size for web applications. ```ts import OBSWebSocket from 'obs-web-socket/json'; ``` -------------------------------- ### Apply Once Properties Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/samples/web-tester/dist/tester.html Marks a virtual node as static and once for optimization. Used for elements rendered only once. ```javascript function pe(t,e,n){return de(t,"__once_"+e+(n?"_"+n:"",!0),t)} ``` -------------------------------- ### Write Integer to Buffer (LE/BE) Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/samples/web-tester/dist/tester.html Methods for writing signed integers of various sizes (8, 16, 32 bits) into a buffer in Little-Endian (LE) or Big-Endian (BE) format. Includes checks for value range and type support. ```javascript l.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||Y(this,e,t,1,127,-128),l.TYPED_ARRAY_SUPPORT||(e=o(e)),0>e&&(e=255+e+1),this[t]=255&e,t+1},l.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||Y(this,e,t,2,32767,-32768),l.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):D(this,e,t,!0),t+2},l.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||Y(this,e,t,2,32767,-32768),l.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):D(this,e,t,!1),t+2},l.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||Y(this,e,t,4,2147483647,-2147483648),l.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):G(this,e,t,!0),t+4},l.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||Y(this,e,t,4,2147483647,-2147483648),0>e&&(e=4294967295+e+1),l.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):G(this,e,t,!1),t+4} ``` -------------------------------- ### OBS WebSocket Connection Establishment Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/samples/web-tester/dist/tester.html Internal method to establish the WebSocket connection. Handles onerror, onopen, and onclose events. Emits 'ConnectionOpened' and 'ConnectionClosed' events. ```javascript async _connect(e){return new Promise((t,n)=>{let r=!1;a('Attempting to connect to: %s',e),this._socket=new o('ws://'+e),this._socket.onerror=(e)=>{return r?(l(a,'Unknown Socket Error',e),void this.emit('error',e)):void(r=!0,l(a,'Websocket Connection failed:',e),n(i.CONNECTION_ERROR))},this._socket.onopen=()=>{r||(this._connected=!0,r=!0,a('Connection opened: %s',e),this.emit('ConnectionOpened'),t())},this._socket.onclose=()=>{this._connected=!1,a('Connection closed: %s',e),this.emit('ConnectionClosed')},this._socket.onmessage=(e)=>{a('["OnMessage"]: %o',e);const t=u(JSON.parse(e.data));let n,o;'error'===t.status?n=t:o=t,t.messageId?this.emit(`obs:internal:message:id-${t.messageId}`,n,o):t.updateType?this.emit(t.updateType,o):(l(a,'Unrecognized Socket Message:',t),this.emit('message',t))}})} ``` -------------------------------- ### Vue Constructor Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/samples/web-tester/dist/tester.html Defines the base Vue constructor, initializing components and providing core functionalities. ```javascript function $e(t){this._init(t)} ``` -------------------------------- ### Connecting to OBS WebSocket Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/README.md Establishes a connection to the OBS WebSocket server. It allows specifying the WebSocket URL, an optional password for authentication, and identification parameters for initial handshake. ```APIDOC ## connect ### Description Connects to the OBS WebSocket server. Allows specifying the WebSocket URL, an optional password, and identification parameters. ### Method Signature ```ts connect(url = 'ws://127.0.0.1:4455', password?: string, identificationParams = {}): Promise ``` ### Parameters #### Path Parameters - `url` (string, optional) - Websocket URL to connect to, including protocol. Defaults to 'ws://127.0.0.1:4455'. - `password` (string, optional) - Password required to authenticate with the OBS WebSocket server. - `identificationParams` (object, optional) - Object with parameters to send with the Identify message. Use this to include RPC version to guarantee compatibility with the server. ### Returns - A promise that resolves with data from Hello and Identified messages or rejects with a connection error. ``` -------------------------------- ### Subscribe to OBS Events with obs-websocket-js Source: https://context7.com/obs-websocket-community-projects/obs-websocket-js/llms.txt Use `obs.on()` to subscribe to real-time events. The client extends EventEmitter3, making its full API available. High-volume events require explicit subscription via the `eventSubscriptions` bitmask in `connect()` or `reidentify()`. ```typescript import OBSWebSocket, { EventSubscription, type OBSEventTypes, } from 'obs-websocket-js'; const obs = new OBSWebSocket(); // --- Internal connection events --- obs.on('ConnectionOpened', () => console.log('WebSocket opened')); obs.on('ConnectionClosed', (err) => console.log(`Closed [${err.code}]: ${err.message}`)); obs.on('ConnectionError', (err) => console.error('Error:', err.message)); obs.on('Hello', (data) => console.log('Hello from OBS', data.obsWebSocketVersion)); obs.on('Identified', (data) => console.log('Identified, RPC:', data.negotiatedRpcVersion)); // --- OBS Scene events --- obs.on('CurrentProgramSceneChanged', ({ sceneName, sceneUuid }) => { console.log(`Scene changed to: ${sceneName} (${sceneUuid})`); }); obs.on('SceneCreated', ({ sceneName, isGroup }) => { console.log(`New ${isGroup ? 'group' : 'scene'}: ${sceneName}`); }); // --- Input / Audio events --- obs.on('InputMuteStateChanged', ({ inputName, inputMuted }) => { console.log(`${inputName} is now ${inputMuted ? 'muted' : 'unmuted'}`); }); obs.on('InputVolumeChanged', ({ inputName, inputVolumeDb }) => { console.log(`${inputName} volume: ${inputVolumeDb.toFixed(1)} dB`); }); // --- High-volume: volume meters (must be subscribed explicitly) --- obs.on('InputVolumeMeters', ({ inputs }) => { for (const input of inputs) { // input.inputLevelsMul is [[left_magnitude, left_peak, left_input_peak], [right...]] process.stdout.write(`\r${input.inputName}: ${JSON.stringify(input.inputLevelsMul)}`); } }); // --- Streaming / Recording state --- obs.on('StreamStateChanged', ({ outputActive, outputState }) => { console.log(`Stream is now ${outputState} (active: ${outputActive})`); }); obs.on('RecordStateChanged', ({ outputActive, outputState, outputPath }) => { if (!outputActive && outputPath) { console.log(`Recording saved to: ${outputPath}`); } }); // --- One-time shutdown listener --- obs.once('ExitStarted', () => { console.log('OBS is shutting down'); obs.disconnect(); }); // --- Vendor plugin events --- obs.on('VendorEvent', ({ vendorName, eventType, eventData }) => { if (vendorName === 'my-plugin') { console.log(`Plugin event [${eventType}]:`, eventData); } }); // --- Custom broadcast events from other clients --- obs.on('CustomEvent', ({ eventData }) => { console.log('Custom event received:', eventData); }); // --- TypeScript: typed handler function --- function onProfileChanged(event: OBSEventTypes['CurrentProfileChanged']) { console.log('Profile changed to:', event.profileName); } obs.on('CurrentProfileChanged', onProfileChanged); obs.off('CurrentProfileChanged', onProfileChanged); // unsubscribe // Connect with explicit high-volume subscription await obs.connect('ws://127.0.0.1:4455', 'password', { eventSubscriptions: EventSubscription.All | EventSubscription.InputVolumeMeters, }); ``` -------------------------------- ### Initialize Component Event Bus Source: https://github.com/obs-websocket-community-projects/obs-websocket-js/blob/master/samples/web-tester/dist/tester.html Initializes the event bus for a component, setting up listeners based on parent component's options. Crucial for inter-component communication. ```javascript function yt(t,e,n){uo=t,et(e,n||{},ht,mt,t)} ```