---
title: "Capture game frames with audio in C#"
url: https://recursiveai.org/onegame/cookbook/capture-game-frames-with-audio/
description: "Capture a bounded sequence of game PNG frames and the mixed WAV audio in C# with onegame. Check frame count and playback duration."
version: "2.0.0"
---

# Capture game frames with audio in C#

**onegame** is a free, open-source game engine for .NET from Recursive AI. MIT or Apache-2.0, no editor required.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneGame.Control) · [GitHub](https://github.com/recursive-ai-oss/onegame) · [Docs](https://recursiveai.org/onegame/docs/) · [Download example (.zip)](https://recursiveai.org/onegame/cookbook/capture-game-frames-with-audio/capture-game-frames-with-audio.zip)

Capture onegame PNG frames and the game’s mixed sound as a WAV.

```shell
dotnet add package RecursiveAI.OneGame.Control
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

`ClipGame.cs` below draws the scene; `tone.wav` is a generated tone in the zip.

```csharp
using OneGame.Audio;
using OneGame.Control;
using OneGame.Host;
using var game = GameInstance.Create(
    new ClipGame(), new GameOptions
    { Headless = true, Gpu = GpuMode.Off });
using var audio = AudioService.Create(
    new AudioServiceOptions { Capture = true });
using var input = File.OpenRead("tone.wav");
audio.Play(audio.LoadSound(input, "tone"),
    new PlayOptions { Loop = true });
var control = new ControlSurface(
    game, "artifacts") { Audio = audio };
control.Call("capture_sequence", """
    {"dir":"clip","count":6,"fps":60}
    """);
Console.WriteLine(
    "Wrote 6 PNGs and audio.wav");
```

```text
Wrote 6 PNGs and audio.wav
```

Unzip [the example](https://recursiveai.org/onegame/cookbook/capture-game-frames-with-audio/capture-game-frames-with-audio.zip), then `dotnet run`.

## The full program

The capture writes `artifacts/clip/frame-0000.png` through `frame-0005.png`, `manifest.json` and `audio.wav`. This headless example renders on the CPU and plays a looping tone into the game mix. The tone is an original 440 Hz sine wave dedicated to the public domain under CC0-1.0; no download or recorded input is needed.

**Scene input: `ClipGame.cs`.** Add this file beside `Program.cs` (it is also in the zip).

```csharp
using OneGame.Core;
using OneGame.Host;
using OneGame.UI;

public sealed class ClipGame : GameDefinition
{
    public override string Name => "clip";
    public override void RegisterEntities(EntityRegistry registry) { }
    public override void Setup(World world) { }
    public override void DefineScreens(ScreenSet screens) =>
        screens.Add("main", _ => Ui.Label("Recording")
            .TextColor(Color.White).Background(Color.Rgb(0x203040)));
}
```

The full program reads the WAV’s format and data chunks and checks its sample-frame count against the requested playback duration.

```csharp
using System.Text.Json;
using OneGame.Audio;
using OneGame.Control;
using OneGame.Core;
using OneGame.Host;
using OneGame.UI;

using var game = GameInstance.Create(new ClipGame(),
    new GameOptions { Headless = true, Gpu = GpuMode.Off });
using var audio = AudioService.Create(
    new AudioServiceOptions { Capture = true });
using var input = File.OpenRead("tone.wav");
var sound = audio.LoadSound(input, "tone");
audio.Play(sound, new PlayOptions { Loop = true });
var control = new ControlSurface(game, "artifacts") { Audio = audio };
var result = control.Call("capture_sequence", """
    {"dir":"clip","count":6,"ticksPerFrame":1,"fps":60,"width":160,"height":90}
    """);
using var reply = JsonDocument.Parse(result);
if (!reply.RootElement.TryGetProperty("wav", out var wav))
    throw new InvalidOperationException(result);
var pngCount = Directory.GetFiles("artifacts/clip", "frame-*.png").Length;
using var reader = new BinaryReader(File.OpenRead(wav.GetString()!));
reader.ReadBytes(12);
uint rate = 0;
ushort blockAlign = 0;
uint dataBytes = 0;
while (reader.BaseStream.Position + 8 <= reader.BaseStream.Length)
{
    var tag = new string(reader.ReadChars(4));
    var size = reader.ReadUInt32();
    var next = reader.BaseStream.Position + size + (size & 1);
    if (tag == "fmt ")
    {
        reader.ReadUInt16(); reader.ReadUInt16();
        rate = reader.ReadUInt32(); reader.ReadUInt32();
        blockAlign = reader.ReadUInt16();
    }
    if (tag == "data") dataBytes = size;
    reader.BaseStream.Position = next;
}
var samples = dataBytes / blockAlign;
if (pngCount != 6 || samples != rate / 10)
    throw new InvalidOperationException("Unexpected capture length.");
Console.WriteLine($"PNG frames: {pngCount}");
Console.WriteLine($"WAV sample frames: {samples} at {rate} Hz");
Console.WriteLine($"Playback duration: {(double)samples / rate:0.000} seconds");
```

```text
PNG frames: 6
WAV sample frames: 4800 at 48000 Hz
Playback duration: 0.100 seconds
```

Invalid capture counts or frame rates return a control error; optional MP4 encoding can fail or be skipped while the PNGs and WAV remain available.

## Variations

For half-speed playback, replace the full program’s capture request with this one, and change the sample-count assertion to `samples != rate / 5`:

```csharp
// control is the ControlSurface created in the full program.
var result = control.Call("capture_sequence", """
    {"dir":"clip","count":6,"ticksPerFrame":1,"fps":30,"width":160,"height":90}
    """);
```

```text
PNG frames: 6
WAV sample frames: 9600 at 48000 Hz
Playback duration: 0.200 seconds
```

Use a new output directory for each sequence so old frames aren’t mistaken for new ones.

## Related recipes

- [Capture and compare screenshots](https://recursiveai.org/onegame/cookbook/screenshot-tests/)
- [Play a sound effect](https://recursiveai.org/onegame/cookbook/play-sound-effect/)
- [Record and replay simulation state](https://recursiveai.org/onegame/cookbook/record-and-replay/)

## The short answer

Call `capture_sequence` on a `ControlSurface` attached to your running onegame instance. Set a bounded frame count, ticks between frames and playback frame rate. The operation writes numbered PNGs, a manifest and a WAV that covers the captured playback span. It does not record the desktop or microphone.

The example uses six frames at 60 frames per second, so the WAV contains 0.100 seconds of audio: 4,800 sample frames at 48,000 Hz. This is playback duration, not a measurement of how long capture takes. A stereo sample frame contains one sample for each channel; it is not the same thing as an image frame.

## How do I record gameplay on PC with audio?

For a onegame project, capture from inside the engine rather than selecting a desktop window. The C# API above works in a headless run, and the [driving guide](https://recursiveai.org/onegame/docs/driving-a-game/) also documents live control and the development runner’s sequence switches. The captured scene is the game’s rendered output. It is not a general recorder for other games.

The capture request’s `count` controls the number of PNGs. `ticksPerFrame` controls simulation stepping between images. `fps` controls how those images play back and therefore the WAV span. Use the default frame rate, the tick rate divided by ticks per frame, for normal-speed playback. Lowering playback fps without changing simulation stepping stretches the sequence; it does not add more simulation frames.

The first PNG is captured at the current tick. Subsequent images follow the requested number of ticks. The manifest records the image filenames, ticks and state hashes, so retain it alongside the PNGs when investigating a particular capture. The WAV begins at the first frame and includes the full playback span, including the last image’s display interval.

Counts are limited to 1 through 3,600 frames, ticks per frame must be at least one, and fps must be between 1 and 1,000. There is also an audio sample limit. These checks prevent an unbounded capture request; choose a short sequence while testing scene setup.

## Does screen capture capture sound?

This operation captures the game mix separately from the images. An active audio service contributes its mixed output, including silence. A game with no audio service still gets a silent WAV. The program explicitly supplies `Audio = audio` so the control surface uses the service playing the tone.

During sequence capture, the device is silenced and the mixer advances by exact sample counts rather than wall-clock time. Integer sample boundaries avoid accumulated rounding error. If the playback duration does not divide evenly into samples, the WAV is rounded down by less than one sample. The [capture documentation](https://recursiveai.org/onegame/docs/driving-a-game/#recording-a-clip-with-sound) describes identical WAV bytes for the same initial state and sounds in headless and stepped runs; it does not promise identical audio after changing the initial state or sound schedule.

PNG and WAV output need no external encoder. If ffmpeg is on PATH and encoding succeeds, the response also supplies an MP4 path. Otherwise `mp4SkipReason` explains why it was skipped. MP4 is an optional packaging step: keep the PNGs, manifest and WAV as the capture’s primary outputs rather than treating a missing video file as a missing capture.
