OBS Studio Control via WebSocket
This guide demonstrates how to control OBS Studio programmatically using Python. It uses the obsws-python library to communicate with the OBS WebSocket server (standard in OBS Studio 28+).
Modules Used:
obsws-python: The official Python library for OBS WebSocket v5.
Prerequisites
- Install OBS Studio (Version 28 or newer recommended).
- Enable WebSocket Server:
- Open OBS Studio.
- Go to Tools -> WebSocket Server Settings.
- Check Enable WebSocket server.
- Note the Server Port (default
4455) and Server Password.
Installation
pip install obsws-python
The Code
Save this as obs_control.py.
import obsws_python as obs
import time
import sys
# Configuration (Match these with your OBS WebSocket Settings)
HOST = 'localhost'
PORT = 4455
PASSWORD = 'your_password_here'
def main():
try:
# 1. Connect to OBS
# ReqClient is used to send requests (commands) to OBS
client = obs.ReqClient(host=HOST, port=PORT, password=PASSWORD)
version = client.get_version()
print(f"Connected to OBS Studio {version.obs_version}")
print(f"WebSocket Version: {version.obs_web_socket_version}")
# 2. Get Current Scene
current_scene = client.get_current_program_scene().current_program_scene_name
print(f"Current Scene: {current_scene}")
# 3. List All Scenes
print("\nAvailable Scenes:")
scenes = client.get_scene_list().scenes
for s in scenes:
# 'sceneName' key might vary slightly depending on version, usually it's 'sceneName'
name = getattr(s, 'scene_name', s.get('sceneName'))
print(f" - {name}")
# 4. Get Stream Status
status = client.get_stream_status()
print(f"\nStreaming Active: {status.output_active}")
print(f"Stream Timecode: {status.output_timecode}")
# --- Examples of Actions (Uncomment to use) ---
# Switch Scene
# client.set_current_program_scene("Scene 2")
# print("Switched to Scene 2")
# Toggle Recording
# client.toggle_record()
# print("Toggled recording")
except Exception as e:
print(f"Error: {e}")
print("Ensure OBS is running and WebSocket server is enabled.")
if __name__ == "__main__":
main()
Usage
- Ensure OBS is running.
- Update the
PASSWORDvariable in the script. - Run the script:
python obs_control.py