Flutter OBS WebSocket通信插件obs_ws的使用

发布于 1周前 作者 caililin 来自 Flutter

Flutter OBS WebSocket通信插件obs_ws的使用

此Dart库提供了通过obs-websocket插件协议与OBS Studio进行通信的方法。

所有请求、响应、事件和枚举都是根据obs-websocket协议使用generate_protocol.py脚本自动生成的。所有请求/响应名称和字段与协议中指定的相同,或为了适应Dart函数/类命名约定而进行了轻微更改(例如,将PascalCase转换为camelCase)。

快速开始

一个使用这些示例的可运行程序可以在example/example.dart中找到。

添加包到pubspec.yaml

dependencies:
  obs_ws: ^1.0.0

导入包

import 'package:obs_ws/obs_ws.dart';

连接到obs-websocket

void main() async {
  OBSWebSocket obs = await OBSWebSocket.connect("127.0.0.1",
      password: password, subscriptions: [EventSubscription.all]);
}

发送请求

var res = await obs.getSceneList();
print("Response code: ${res.status.code}");
print("Scenes: ${res.scenes}");

发送批量请求

var req1 = GetSceneListRequest();
var req2 = GetStudioModeEnabledRequest();
var req3 = CreateSceneRequest(sceneName: "Test");
var res = await obs.sendBatchRequest([req1, req2, req3]);

// 如果serializeResponses设置为true(默认值为true),
// 您可以使用每个请求对象的response字段。
print("Request 1 (GetSceneList): ${req1.response?.scenes}");
print("Request 2 (GetStudioModeEnabled): ${req2.response?.studioModeEnabled}");
print("Request 3 (CreateScene) Status: ${req3.response?.status.code.name}");
print("Responses: ${res}");

监听事件

obs.eventStream.listen((event) {
  print("Event type: ${event.type}");
  print("Event data (raw): ${event.data}");

  if (event is StudioModeStateChangedEvent) {
    print("Studio mode status: ${event.studioModeEnabled}");
  }
});

断开连接

await obs.disconnect();

注意,您可以根据需要选择高级或低级的方式。例如,如果您不想使用请求/响应类并希望直接使用JSON,可以使用call方法:

var res = await obs.call("GetInputVolume", {"inputName": "Mic/Aux"});
print(res.data["inputVolumeDb"])

如果想要更底层的操作,可以直接手动发送和接收所有操作码:

String requestId = "meow";

RequestOpCode requestOp = RequestOpCode.create(
  requestType: "GetInputVolume",
  requestId: requestId,
  requestData: {
    "inputName": "Mic/Aux",
  },
);
obs.sendOpCode(requestOp);

RequestResponseOpCode responseOp = await obs.waitForOpCode(WebSocketOpCode.requestResponse);
if (responseOp.requestId == requestId && 
      responseOp.requestStatus.code == RequestStatus.success) {
  print(responseOp.responseData!["inputVolumeDb"]);
}

obs.opCodeStream.listen((event) {
  if (event.code == WebSocketOpCode.event) {
    print("Event type: ${event.data['eventType']}");
    print("Event data: ${event.data['eventData']}");
  }
});

当使用OBSWebSocket.connectOBSWebSocket.connectUri时,如果auto设置为false,也可以手动完成Hello-Identify-Identified过程。

示例代码

以下是一个完整的示例代码,展示了如何使用obs_ws插件与OBS Studio进行通信:

import 'package:obs_ws/obs_ws.dart';

// Put obs-websocket password here
const String password = "";

void main() async {
  // Connect to obs-websocket
  OBSWebSocket obs = await OBSWebSocket.connect("127.0.0.1",
      password: password, subscriptions: [EventSubscription.all]);

  // Listen for events
  obs.eventStream.listen((event) {
    print("Event emitted: ${event.type}");
    print("Event data: ${event.data}");

    if (event is SceneTransitionStartedEvent) {
      print("Transitioning: ${event.transitionName}");
    } else if (event is StudioModeStateChangedEvent) {
      print("Studio mode: ${event.studioModeEnabled}");
    }
  });

  // Send requests and print responses
  // Note that these helper functions are provided as an extension on [OBSWebSocket]
  var sceneList = await obs.getSceneList();
  var currentScene = await obs.getCurrentProgramScene();
  var profileList = await obs.getProfileList();
  print("GetSceneList: ${sceneList.scenes}");
  print("GetCurrentProgramScene: ${currentScene.currentProgramSceneName}");
  print("GetProfileList: ${profileList.profiles}");
  await Future.delayed(Duration(seconds: 2));

  // Second method to send requests
  GetCurrentProgramSceneRequest request = GetCurrentProgramSceneRequest();
  GetCurrentProgramSceneResponse response = await obs.sendRequest(request);
  print(response.currentProgramSceneName);
  // Or get the response from the request object
  print(request.response?.currentProgramSceneName);
  await Future.delayed(Duration(seconds: 2));

  // Third method to send requests
  var call = await obs.call("GetCurrentProgramScene");
  print(call.data["currentProgramSceneName"]);

  // Send batch request
  var req1 = GetSceneListRequest();
  var req2 = GetStudioModeEnabledRequest();
  var req3 = CreateSceneRequest(sceneName: "Test");
  var batchReq = await obs.sendBatchRequest([req1, req2, req3],
      executionType: RequestBatchExecutionType.serialRealtime);
  var res1 = req1.response!;
  var res2 = req2.response!;
  var res3 = req3.response!;
  print("Request 1 (GetSceneList): ${res1.scenes}");
  print("Request 2 (GetStudioModeEnabled): ${res2.studioModeEnabled}");
  print("Request 3 (CreateScene) Status: ${res3.status.code.name}");
  print("Responses: ${batchReq.toString()}");
  await Future.delayed(Duration(seconds: 2));

  // Disconnect from obs-websocket after 15 seconds
  print("Disconnecting in 15 seconds");
  await Future.delayed(Duration(seconds: 15));
  await obs.disconnect();
}

更多关于Flutter OBS WebSocket通信插件obs_ws的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter OBS WebSocket通信插件obs_ws的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用obs_ws插件与OBS(Open Broadcaster Software)进行WebSocket通信的示例代码。这假设你已经安装并配置好了OBS WebSocket插件,并且OBS正在运行。

首先,确保你已经在你的pubspec.yaml文件中添加了obs_ws依赖:

dependencies:
  flutter:
    sdk: flutter
  obs_ws: ^最新版本号  # 请替换为当前可用的最新版本号

然后运行flutter pub get来安装依赖。

接下来,你可以在你的Flutter项目中创建一个服务或类来管理OBS WebSocket通信。以下是一个简单的示例:

import 'package:flutter/material.dart';
import 'package:obs_ws/obs_ws.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('OBS WebSocket Demo'),
        ),
        body: OBSWebSocketDemo(),
      ),
    );
  }
}

class OBSWebSocketDemo extends StatefulWidget {
  @override
  _OBSWebSocketDemoState createState() => _OBSWebSocketDemoState();
}

class _OBSWebSocketDemoState extends State<OBSWebSocketDemo> {
  late OBSWebSocketClient _obsClient;
  bool _isConnected = false;

  @override
  void initState() {
    super.initState();
    // 初始化OBS WebSocket客户端
    _obsClient = OBSWebSocketClient(
      address: 'ws://localhost:4444', // 替换为你的OBS WebSocket插件地址
      password: 'your_password',      // 替换为你的OBS WebSocket插件密码
    );

    // 连接到OBS WebSocket服务器
    _connectToOBS();
  }

  void _connectToOBS() async {
    try {
      await _obsClient.connect();
      setState(() {
        _isConnected = true;
      });
      print('Connected to OBS WebSocket');

      // 示例:获取OBS当前状态
      _obsClient.sendGetRequest('GetStatus').then((response) {
        print('OBS Status: $response');
      });

      // 示例:开始录制
      // _obsClient.sendPostRequest('StartRecording', {'scene-name': 'Scene 1'}).then((response) {
      //   print('Recording started: $response');
      // });

      // 示例:停止录制
      // _obsClient.sendPostRequest('StopRecording').then((response) {
      //   print('Recording stopped: $response');
      // });

    } catch (e) {
      print('Failed to connect to OBS WebSocket: $e');
    }
  }

  @override
  void dispose() {
    // 断开连接
    if (_isConnected) {
      _obsClient.disconnect();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text('OBS WebSocket Demo'),
          SizedBox(height: 20),
          Text(_isConnected ? 'Connected to OBS' : 'Not Connected'),
        ],
      ),
    );
  }
}

注意事项:

  1. 替换地址和密码:确保将ws://localhost:4444替换为你的OBS WebSocket插件的实际地址,将your_password替换为你的OBS WebSocket插件的密码。
  2. 权限:确保OBS WebSocket插件在OBS中已启用,并且你有正确的权限来发送请求。
  3. 依赖版本:检查obs_ws插件的最新版本,并在pubspec.yaml中更新。

这个示例展示了如何连接到OBS WebSocket服务器,获取OBS的状态,并演示了如何发送请求来开始和停止录制。你可以根据需要扩展这个示例来包含更多功能,比如切换场景、调整设置等。

回到顶部