This tutorial records a file or a live source to a new file with MFWriter. It uses the project and the frame
loop from MFormats 1: Playing a file and
MFormats 2: Capturing from a device.
Open the writer
WriterSet opens the output: a file path or a network URL, and the encoding configuration as a string. The
configuration names the container (format) and the codecs with their options:
private readonly MFWriterClass m_writer = new MFWriterClass();
m_writer.WriterSet(@"C:\Video\capture.mp4", 0,
"format='mp4' video::codec='mpeg4' video::b='5M' audio::codec='aac'");
Pass 0 as the second argument, as the SDK samples do. The available containers and codecs depend on the
installation and can be listed:
m_writer.WriterOptionGetCount(eMFWriterOption.eMFWO_Format, out int count);
for (int i = 0; i < count; i++)
{
m_writer.WriterOptionGetByIndex(eMFWriterOption.eMFWO_Format, i, out string shortName, out string longName);
Console.WriteLine($"{shortName}: {longName}"); // the short name goes to format='...'
}
// eMFWO_VideoCodec and eMFWO_AudioCodec list the codecs
Put the frames to the writer
Add the writer to the loop as one more receiver:
private void RecordLoop(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
m_live.SourceFrameGet(-1, out MFFrame frame, "");
try
{
m_writer.ReceiverFramePut(frame, -1, "");
m_preview.ReceiverFramePut(frame, 0, "");
}
finally
{
Marshal.ReleaseComObject(frame);
}
}
}
With a live source the loop runs at the rate of the signal. With a file as the source and no preview that waits, nothing slows the loop down: the writer encodes as fast as it can, which is the way to transcode a file.
Close the file
Stop the loop first, then close the writer. WriterClose(0) returns after the file is complete; with
1 the file is finished in the background. A file that is not closed (for example after the process is
killed) may not play.
StopRecording(); // cancel the token and join the thread
m_writer.WriterClose(0);
Marshal.ReleaseComObject(m_writer);
Next steps
- Container and codec options: Audio and video codecs and MFWriter object properties.
- The SDK sample
Sample File Writingrecords files and network streams from a file or a device.
Still have questions?
Tell us what didn’t work or what you’d like clarified.