|
| 1 | +using ObsKit.NET; |
| 2 | +using ObsKit.NET.Outputs; |
| 3 | +using ObsKit.NET.Sources; |
| 4 | + |
| 5 | +Console.WriteLine("ObsKit.NET - Streaming Example"); |
| 6 | +Console.WriteLine("==============================\n"); |
| 7 | + |
| 8 | +// OBS runtime should be set up alongside the application. |
| 9 | +// See README.md for instructions on setting up the OBS runtime. |
| 10 | + |
| 11 | +var obsPath = AppContext.BaseDirectory; |
| 12 | +var dataPath = Path.Combine(obsPath, "data", "libobs"); |
| 13 | +var pluginBinPath = Path.Combine(obsPath, "obs-plugins", "64bit"); |
| 14 | +var pluginDataPath = Path.Combine(obsPath, "data", "obs-plugins", "%module%"); |
| 15 | + |
| 16 | +// Verify OBS runtime exists |
| 17 | +if (!File.Exists(Path.Combine(obsPath, "obs.dll"))) |
| 18 | +{ |
| 19 | + Console.WriteLine("ERROR: OBS runtime not found!"); |
| 20 | + Console.WriteLine($"Expected obs.dll at: {obsPath}"); |
| 21 | + Console.WriteLine("\nPlease set up the OBS runtime. See README.md for instructions."); |
| 22 | + return; |
| 23 | +} |
| 24 | + |
| 25 | +// Initialize OBS |
| 26 | +using var obs = Obs.Initialize(config => config |
| 27 | + .WithDataPath(dataPath) |
| 28 | + .WithModulePath(pluginBinPath, pluginDataPath) |
| 29 | + .ForHeadlessOperation() |
| 30 | + .WithVideo(v => v.Resolution(1920, 1080).Fps(30)) // 30 FPS is common for streaming |
| 31 | + .WithAudio(a => a.WithSampleRate(48000))); |
| 32 | + |
| 33 | +Console.WriteLine($"OBS {Obs.Version} initialized\n"); |
| 34 | + |
| 35 | +// Set up capture source (monitor capture in this example) |
| 36 | +var primaryMonitor = MonitorCapture.AvailableMonitors.FirstOrDefault(m => m.IsPrimary) |
| 37 | + ?? MonitorCapture.AvailableMonitors.First(); |
| 38 | +using var monitorSource = MonitorCapture.FromMonitor(primaryMonitor) |
| 39 | + .SetCaptureMethod(MonitorCaptureMethod.DesktopDuplication); |
| 40 | + |
| 41 | +// Adjust video resolution to match monitor |
| 42 | +Obs.SetVideo(v => v.Resolution((uint)primaryMonitor.Width, (uint)primaryMonitor.Height).Fps(30)); |
| 43 | + |
| 44 | +// Set up audio sources |
| 45 | +using var audioInput = AudioInputCapture.FromDefault(); |
| 46 | +using var audioOutput = AudioOutputCapture.FromDefault(); |
| 47 | + |
| 48 | +// Create a scene with monitor capture |
| 49 | +using var scene = Obs.Scenes.Create("Streaming Scene"); |
| 50 | +scene.AddSource(monitorSource); |
| 51 | +scene.AddSource(audioInput); |
| 52 | +scene.AddSource(audioOutput); |
| 53 | +scene.SetAsProgram(); |
| 54 | + |
| 55 | +Console.WriteLine($"Scene created with {scene.ItemCount} source(s)\n"); |
| 56 | + |
| 57 | +// ======================================== |
| 58 | +// STREAMING CONFIGURATION |
| 59 | +// ======================================== |
| 60 | +// Replace these values with your actual stream key and server! |
| 61 | + |
| 62 | +// Option 1: Stream to a custom RTMP server |
| 63 | +//const string rtmpServer = "rtmp://localhost/live"; // Your RTMP server URL |
| 64 | +//const string streamKey = "test-stream-key"; // Your stream key |
| 65 | + |
| 66 | +// Option 2: Stream to Twitch (uncomment and set your stream key) |
| 67 | +const string twitchStreamKey = "live_xxxxxxxx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; |
| 68 | + |
| 69 | +// Option 3: Stream to YouTube (uncomment and set your stream key) |
| 70 | +// const string youtubeStreamKey = "xxxx-xxxx-xxxx-xxxx-xxxx"; |
| 71 | + |
| 72 | +// Create streaming output |
| 73 | +using var streaming = new StreamingOutput("My Stream") |
| 74 | + // Configure destination - choose ONE of the following: |
| 75 | + |
| 76 | + // Custom RTMP server: |
| 77 | + //.ToCustomServer(rtmpServer, streamKey) |
| 78 | + |
| 79 | + // Or Twitch: |
| 80 | + .ToTwitch(twitchStreamKey) |
| 81 | + |
| 82 | + // Or YouTube: |
| 83 | + // .ToYouTube(youtubeStreamKey) |
| 84 | + |
| 85 | + // Or Facebook: |
| 86 | + // .ToFacebook(facebookStreamKey) |
| 87 | + |
| 88 | + // Or use a Service directly for full control: |
| 89 | + // .WithService(Service.CreateCustom(rtmpServer, streamKey)) |
| 90 | + |
| 91 | + // Configure encoders |
| 92 | + // For streaming, lower bitrates are typically used (4500 kbps is common for 1080p) |
| 93 | + // This is the equivalent of setting the encoders above like |
| 94 | + // .WithVideoEncoder(VideoEncoder.CreateH264("Streaming Video", 4500, 1920, 1080, 30, "veryfast")) |
| 95 | + // .WithAudioEncoder(AudioEncoder.CreateAac("Streaming Audio", 160)) |
| 96 | + .WithDefaultEncoders(videoBitrate: 4500, audioBitrate: 160, preset: "veryfast") |
| 97 | + |
| 98 | + // Or use NVENC if you have an NVIDIA GPU: |
| 99 | + // .WithNvencEncoders(videoBitrate: 6000, audioBitrate: 160) |
| 100 | + |
| 101 | + // Optional: Configure reconnection |
| 102 | + .WithReconnect(enabled: true, retryDelaySec: 10, maxRetries: 20) |
| 103 | + |
| 104 | + // Optional: Enable low latency mode for reduced delay |
| 105 | + .WithLowLatencyMode(enabled: true); |
| 106 | + |
| 107 | +Console.WriteLine("Streaming Configuration:"); |
| 108 | +Console.WriteLine($" Server: {streaming.Url}"); |
| 109 | +Console.WriteLine($" Can connect: {streaming.Service?.CanConnect}"); |
| 110 | +Console.WriteLine(); |
| 111 | + |
| 112 | +// Connect to streaming events |
| 113 | +using var startedHandler = streaming.OnStarted(() => |
| 114 | +{ |
| 115 | + Console.WriteLine("[Event] Stream started successfully!"); |
| 116 | +}); |
| 117 | + |
| 118 | +using var stoppedHandler = streaming.OnStopped(code => |
| 119 | +{ |
| 120 | + Console.WriteLine($"[Event] Stream stopped with code: {code}"); |
| 121 | +}); |
| 122 | + |
| 123 | +using var reconnectingHandler = streaming.OnReconnecting(() => |
| 124 | +{ |
| 125 | + Console.WriteLine("[Event] Connection lost, attempting to reconnect..."); |
| 126 | +}); |
| 127 | + |
| 128 | +using var reconnectedHandler = streaming.OnReconnected(() => |
| 129 | +{ |
| 130 | + Console.WriteLine("[Event] Reconnected successfully!"); |
| 131 | +}); |
| 132 | + |
| 133 | +// Start streaming |
| 134 | +Console.WriteLine("Starting stream... Press any key to stop.\n"); |
| 135 | + |
| 136 | +if (!streaming.Start()) |
| 137 | +{ |
| 138 | + Console.WriteLine($"Failed to start stream: {streaming.LastError}"); |
| 139 | + return; |
| 140 | +} |
| 141 | + |
| 142 | +Console.WriteLine("Streaming in progress...\n"); |
| 143 | + |
| 144 | +// Display stats periodically |
| 145 | +var cts = new CancellationTokenSource(); |
| 146 | +var statsTask = Task.Run(async () => |
| 147 | +{ |
| 148 | + while (!cts.Token.IsCancellationRequested) |
| 149 | + { |
| 150 | + await Task.Delay(2000, cts.Token).ConfigureAwait(false); |
| 151 | + if (streaming.IsActive) |
| 152 | + { |
| 153 | + var mbSent = streaming.TotalBytes / 1024.0 / 1024.0; |
| 154 | + Console.WriteLine($" Stats: {streaming.TotalFrames} frames, {mbSent:F2} MB sent, {streaming.FramesDropped} dropped, congestion: {streaming.Congestion:P0}, delay: {streaming.ActiveDelay}"); |
| 155 | + } |
| 156 | + } |
| 157 | +}, cts.Token); |
| 158 | + |
| 159 | +// Wait for user to stop |
| 160 | +Console.ReadKey(intercept: true); |
| 161 | +cts.Cancel(); |
| 162 | + |
| 163 | +// Stop streaming |
| 164 | +Console.WriteLine("\nStopping stream..."); |
| 165 | +streaming.Stop(); |
| 166 | + |
| 167 | +Console.WriteLine("\nStream ended!"); |
| 168 | +Console.WriteLine($" Total frames: {streaming.TotalFrames}"); |
| 169 | +Console.WriteLine($" Total bytes: {streaming.TotalBytes:N0}"); |
| 170 | +Console.WriteLine($" Frames dropped: {streaming.FramesDropped}"); |
0 commit comments