MP3 Encoder (Pull)

This article explains how you can use {transcoder-pull-net} to encode a WAV file to MP3 (MPEG Audio Layer III) format.

The code snippets in this article are from the enc_mp3_pull .NET sample.

Source Audio

For source we use the equinox-48KHz.wav file from the AVBlocks Assets repository. After downloading and unzipping you will find equinox-48KHz.wav in the aud subdirectory.

Code

This code takes a WAV file and encodes it to compressed MP3 format using the pull method. The encoded samples are pulled from the transcoder and written to the output file by the application.

Initialize AVBlocks

Initialize the AVBlocks library before creating the transcoder, and shut it down after encoding is complete.

static int Main(string[] args)
{
    var opt = new Options();

    if (!opt.Prepare(args))
        return opt.Error ? (int)ExitCodes.OptionsError : (int)ExitCodes.Success;

    Library.Initialize();

    // Set license information. Without this AVBlocks runs in Demo mode.
    // Library.SetLicense("<license-string>");

    bool encodeResult = Encode(opt);

    Library.Shutdown();

    return encodeResult ? (int)ExitCodes.Success : (int)ExitCodes.EncodingError;
}

Configure Input Socket

The input socket describes the WAV source file. The transcoder auto-detects the audio format from the file.

static MediaSocket CreateInputSocket(Options opt)
{
    MediaSocket socket = new MediaSocket();
    socket.File = opt.InputFile;
    return socket;
}

Configure Output Socket

The output socket describes MP3 output. The pull sample does not set a file on the output socket because the application writes pulled samples to the output stream.

static MediaSocket CreateOutputSocket()
{
    MediaSocket socket = new MediaSocket();
    socket.StreamType = StreamType.MpegAudio;
    socket.StreamSubType = StreamSubType.MpegAudioLayer3;

    MediaPin pin = new MediaPin();
    socket.Pins.Add(pin);

    AudioStreamInfo asi = new AudioStreamInfo();
    pin.StreamInfo = asi;

    asi.StreamType = StreamType.MpegAudio;
    asi.StreamSubType = StreamSubType.MpegAudioLayer3;

    // The default bitrate is 128000. You can set it to 192000, 256000, etc.
    // asi.Bitrate = 192000;

    // Optionally set the sampling rate and the number of the channels, e.g. 44.1 Khz, Mono
    // asi.SampleRate = 44100;
    // asi.Channels = 1;

    return socket;
}

Configure Transcoder and Pull Encoded Samples

After creating the input and output sockets, the sample creates a transcoder, enables demo mode, opens it, pulls encoded samples, writes each sample buffer to the output file, and checks for end-of-stream.

static bool Encode(Options opt)
{
    // transcoder will fail if output exists (by design)
    DeleteFile(opt.OutputFile);

    // Create output directory if needed
    string outputDir = Path.GetDirectoryName(opt.OutputFile);
    if (!string.IsNullOrEmpty(outputDir))
        Directory.CreateDirectory(outputDir);

    using (FileStream outfile = File.Create(opt.OutputFile))
    {
        MediaSocket inSocket = CreateInputSocket(opt);
        MediaSocket outSocket = CreateOutputSocket();

        // create Transcoder
        using (Transcoder transcoder = new Transcoder())
        {
            transcoder.AllowDemoMode = true;
            transcoder.Inputs.Add(inSocket);
            transcoder.Outputs.Add(outSocket);

            if (!transcoder.Open())
            {
                PrintError("Transcoder open", transcoder.Error);
                return false;
            }

            // encode by pulling encoded samples
            int outputIndex = 0;
            MediaSample sample = new MediaSample();

            while (transcoder.Pull(out outputIndex, sample))
            {
                outfile.Write(sample.Buffer.Start, sample.Buffer.DataOffset, sample.Buffer.DataSize);
            }

            ErrorInfo error = transcoder.Error;
            PrintError("Transcoder pull", error);

            bool success = false;
            if (error.Facility == ErrorFacility.Codec &&
                error.Code == (int)CodecError.EOS)
            {
                // ok
                success = true;
            }

            transcoder.Close();

            return success;
        }
    }
}

Complete Code

Here’s the complete working example that demonstrates MP3 encoding using the pull method with AVBlocks for .NET.

using System;
using System.IO;
using PrimoSoftware.AVBlocks;

namespace CliSample
{
    class Program
    {
        static int Main(string[] args)
        {
            var opt = new Options();

            if (!opt.Prepare(args))
                return opt.Error ? (int)ExitCodes.OptionsError : (int)ExitCodes.Success;

            Library.Initialize();

            // Set license information. Without this AVBlocks runs in Demo mode.
            // Library.SetLicense("<license-string>");

            bool encodeResult = Encode(opt);

            Library.Shutdown();

            return encodeResult ? (int)ExitCodes.Success : (int)ExitCodes.EncodingError;
        }

        static MediaSocket CreateInputSocket(Options opt)
        {
            MediaSocket socket = new MediaSocket();
            socket.File = opt.InputFile;
            return socket;
        }

        static MediaSocket CreateOutputSocket()
        {
            MediaSocket socket = new MediaSocket();
            socket.StreamType = StreamType.MpegAudio;
            socket.StreamSubType = StreamSubType.MpegAudioLayer3;

            MediaPin pin = new MediaPin();
            socket.Pins.Add(pin);

            AudioStreamInfo asi = new AudioStreamInfo();
            pin.StreamInfo = asi;

            asi.StreamType = StreamType.MpegAudio;
            asi.StreamSubType = StreamSubType.MpegAudioLayer3;

            // The default bitrate is 128000. You can set it to 192000, 256000, etc.
            // asi.Bitrate = 192000;

            // Optionally set the sampling rate and the number of the channels, e.g. 44.1 Khz, Mono
            // asi.SampleRate = 44100;
            // asi.Channels = 1;

            return socket;
        }

        static bool Encode(Options opt)
        {
            // transcoder will fail if output exists (by design)
            DeleteFile(opt.OutputFile);

            // Create output directory if needed
            string outputDir = Path.GetDirectoryName(opt.OutputFile);
            if (!string.IsNullOrEmpty(outputDir))
                Directory.CreateDirectory(outputDir);

            using (FileStream outfile = File.Create(opt.OutputFile))
            {
                MediaSocket inSocket = CreateInputSocket(opt);
                MediaSocket outSocket = CreateOutputSocket();

                // create Transcoder
                using (Transcoder transcoder = new Transcoder())
                {
                    transcoder.AllowDemoMode = true;
                    transcoder.Inputs.Add(inSocket);
                    transcoder.Outputs.Add(outSocket);

                    if (!transcoder.Open())
                    {
                        PrintError("Transcoder open", transcoder.Error);
                        return false;
                    }

                    // encode by pulling encoded samples
                    int outputIndex = 0;
                    MediaSample sample = new MediaSample();

                    while (transcoder.Pull(out outputIndex, sample))
                    {
                        outfile.Write(sample.Buffer.Start, sample.Buffer.DataOffset, sample.Buffer.DataSize);
                    }

                    ErrorInfo error = transcoder.Error;
                    PrintError("Transcoder pull", error);

                    bool success = false;
                    if (error.Facility == ErrorFacility.Codec &&
                        error.Code == (int)CodecError.EOS)
                    {
                        // ok
                        success = true;
                    }

                    transcoder.Close();

                    return success;
                }
            }
        }

        static void DeleteFile(string filename)
        {
            try
            {
                if (File.Exists(filename))
                    File.Delete(filename);
            }
            catch { }
        }

        static void PrintError(string action, ErrorInfo e)
        {
            if (action != null)
            {
                Console.Write("{0}: ", action);
            }

            if (ErrorFacility.Success == e.Facility)
            {
                Console.WriteLine("Success");
                return;
            }
            else
            {
                Console.WriteLine("{0}, facility:{1} code:{2} hint:{3}", e.Message ?? "", e.Facility, e.Code, e.Hint ?? "");
            }
        }

        enum ExitCodes : int
        {
            Success = 0,
            OptionsError = 1,
            EncodingError = 2,
        }
    }
}

How to Run

See the build instructions for macOS and the enc_mp3_pull .NET sample for details.

Command Line

enc_mp3_pull --input <file.wav> --output <file.mp3>

Examples

List options:

./bin/net10.0/enc_mp3_pull --help
Usage: enc_mp3_pull --input <file.wav> --output <file.mp3>
  -i,    --input    input WAV file
  -o,    --output   output MP3 file
  --help            Display this help screen.