---
title: "Mux encoded audio and video into MP4 in C#"
url: https://recursiveai.org/onemedia/cookbook/mux-encoded-audio-and-video-to-mp4/
description: "Use OneMedia’s MP4 muxer to add H.264 and AAC tracks, write encoded packets in decode order, and finalize one file without re-encoding."
version: "1.0.2"
---

Muxing packs already-encoded video and audio streams into one container file, here MP4, without re-encoding.

```shell
dotnet add package RecursiveAI.OneMedia
```

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

Unzip [the example](https://recursiveai.org/onemedia/cookbook/mux-encoded-audio-and-video-to-mp4/mux-encoded-audio-and-video-to-mp4.zip), then `dotnet run`.

The full program uses this helper to write `combined.mp4`:

```csharp
using RecursiveAI.OneMedia;
using RecursiveAI.OneMedia.IsoBmff;

static MuxReport WriteMp4(
    MediaTrack video, MediaTrack audio,
    IEnumerable<(PacketInfo Info,
        byte[] Data)> packets)
{
    using var file = File.Create("combined.mp4");
    using var mux = new IsoMuxer(file);
    int v = mux.AddTrack(video);
    int a = mux.AddTrack(audio);
    foreach (var (info, data) in packets)
    {
        int track =
            info.TrackIndex == video.Index ? v : a;
        var packet = info with { TrackIndex = track };
        mux.WritePacket(packet, data);
    }
    return mux.Finish();
}
```


## The full program

For these codecs, supply length-prefixed H.264 and raw AAC packets without ADTS headers.

The zip contains `video.packets` (two H.264 packets for a blue square, 655 and 13 bytes) and `audio.packets` (12 raw AAC packets for a 440 Hz tone, the first 199 bytes). The files are concatenated packet payloads, not MP4 inputs; the program supplies their boundaries, timing, and decoder setup. The helper expects packets from exactly the two declared tracks, already in the order they should be written.

```csharp
using RecursiveAI.OneMedia;
using RecursiveAI.OneMedia.IsoBmff;

var video = new MediaTrack
{
    Index = 0, Kind = TrackKind.Video, Codec = CodecId.H264,
    Timescale = 8, Video = new(64, 64),
    Configuration = new(Convert.FromHexString(
        "0164000AFFE100186764000AACB2084D" +
        "80880000030008000003008078913240" +
        "01000668EBC3CB22C0FDF8F800"), "avcC")
};
var audio = new MediaTrack
{
    Index = 1, Kind = TrackKind.Audio, Codec = CodecId.Aac,
    Timescale = 48_000, Audio = new(48_000, 1),
    Configuration = new(Convert.FromHexString("118856E500"), "asc")
};

var packets = ReadPackets("video.packets", video, [655, 13], 1)
    .Concat(ReadPackets("audio.packets", audio,
        [199, 90, 94, 104, 107, 117, 132, 145, 129, 149, 108, 159], 1024))
    .OrderBy(packet => packet.Info.Dts);

var report = WriteMp4(video, audio, packets);
Console.WriteLine("Wrote combined.mp4");
Console.WriteLine($"Video packets: {report.Tracks[0].Packets}");
Console.WriteLine($"Audio packets: {report.Tracks[1].Packets}");

static MuxReport WriteMp4(
    MediaTrack video, MediaTrack audio,
    IEnumerable<(PacketInfo Info, byte[] Data)> packets)
{
    using var output = File.Create("combined.mp4");
    using var mux = new IsoMuxer(output);
    int v = mux.AddTrack(video);
    int a = mux.AddTrack(audio);
    foreach (var (info, data) in packets)
    {
        int track = info.TrackIndex == video.Index ? v : a;
        mux.WritePacket(info with { TrackIndex = track }, data);
    }
    return mux.Finish();
}

static IEnumerable<(PacketInfo Info, byte[] Data)> ReadPackets(
    string path, MediaTrack track, int[] sizes, int ticksPerPacket)
{
    using var input = File.OpenRead(path);
    var duration = new MediaTime(ticksPerPacket, track.Timescale);
    for (int i = 0; i < sizes.Length; i++)
    {
        var data = new byte[sizes[i]];
        input.ReadExactly(data);
        var time = new MediaTime(i * (long)ticksPerPacket, track.Timescale);
        var flags = i == 0 || track.Kind == TrackKind.Audio
            ? PacketAttributes.Keyframe : PacketAttributes.None;
        yield return (new(track.Index, time, time, duration,
            flags, ByteRange.None, data.Length), data);
    }
}
```

```text
Wrote combined.mp4
Video packets: 2
Audio packets: 12
```

`MuxRefusedException` exposes a reason if a track is unsupported or lacks required configuration, or if a packet arrives with an out-of-order decode timestamp for its track.

## Variations

To put the MP4 movie metadata at the end and write packet payloads directly to a seekable output file, replace the `IsoMuxer` constructor call:

```csharp
using var mux = new IsoMuxer(output, new IsoMuxOptions
{
    Layout = IsoLayout.MoovLast
});
```

## Related recipes

- [Mux encoded packets into WebM](https://recursiveai.org/onemedia/cookbook/mux-packets-to-webm/)
- [Write a fragmented MP4 from an existing MP4](https://recursiveai.org/onemedia/cookbook/write-fragmented-mp4/)
- [Handle muxer refusals](https://recursiveai.org/onemedia/cookbook/handle-muxer-refusal-errors/)

## The short answer

Use `IsoMuxer.AddTrack` for both tracks before writing packets. Supply the codec configuration and each track’s clock rate, then pass the encoded bytes with a `PacketInfo` carrying decode and presentation timestamps, duration, and flags. Use the output track index returned by `AddTrack`, not the source identifier. Call `Finish()` once after the last packet; disposing the muxer without finishing leaves the MP4 incomplete.

## What does muxing mean?

Muxing means packaging streams together in a container. MP4 describes where their packets are and when to decode and play them. H.264 and AAC describe how the video and audio bytes themselves are encoded. Muxing doesn’t create those bytes from raw frames or samples, and it doesn’t change one codec into another. Demuxing goes the other way: it reads the tracks and packets back out of a container.

The distinction matters at the input boundary. `IsoMuxer` copies packet payloads as supplied; it expects access units already packaged for the target container. For the H.264 example, `avcC` is the track’s decoder configuration and the packet carries length-prefixed NAL units. For the AAC example, the track has an AudioSpecificConfig and the packets are raw, without ADTS headers. If your encoder produces H.264 Annex B start codes or AAC with ADTS headers, repackage those packets before calling `WritePacket`. See the [muxing contract](https://recursiveai.org/onemedia/docs/muxing/) for the required track metadata and refusal reasons.

## What is an example of muxing?

This example combines a video packet at time zero with audio packets that have their own clock. The video clock has eight ticks per second and each picture lasts one tick. The audio clock has 48,000 ticks per second and each AAC packet lasts 1,024 ticks. Comparing the raw tick counts would put packets in the wrong order. The example compares `MediaTime` values instead, which lets the second video packet land between audio packets near its decode time.

Preserve decode order within each track even if presentation times differ. For example, a video frame can need another frame decoded before it, despite being displayed first. In that case, keep both the decode timestamp (DTS) and the presentation timestamp (PTS) from your encoder; don’t sort the write loop by PTS or replace it with DTS. The fixture has no reordered pictures, so its DTS and PTS are equal. For long inputs, merge packet streams in decode order rather than materializing all packets as this small example does.

Finally, the muxer needs to write the file’s tables. The default layout puts the movie metadata before the payload for fast start. `Finish()` completes the file and gives you the reported packet counts. Pick the end-metadata layout for a seekable file if you want the payload written through as you go, or consider fragments when the receiver expects a fragmented stream. The encoded packets and output layout are separate choices.
