AVBlocks™

How to configure output socket for MP3 encoding in .NET

Here is a quick snippet for configuring the output socket of a Transcoder for MP3 encoding using C#.

Diagram

flowchart TB
    is("<b>MediaSocket</b>\nFile: input.wav")
    os("<b>MediaSocket</b>\nType: MpegAudio\nSubtype: MpegAudioLayer3\nFile: output.mp3")
    tr("<b>Transcoder Block</b>\nopen\nrun\nclose")
    out["output.mp3"]

    in["input.wav"]
    out["output.mp3"]

    is --> |"add input"| tr 
    os --> |"add output"| tr
    
    in  --> |"read"| tr --> |"write"| out

Code

This is the code for the output socket:

static MediaSocket CreateOutputSocket(Options opt)
{
    AudioStreamInfo asi = new AudioStreamInfo();
    asi.StreamType = StreamType.MpegAudio;
    asi.StreamSubType = StreamSubType.MpegAudioLayer3;

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

    // You can change the sampling rate and the number of the channels
    // asi.SampleRate = 44100;
    // asi.Channels = 1;

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

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

    socket.Pins.Add(pin);

    // output to a file
    socket.File = opt.OutputFile;

    return socket;
}

The complete program is available on GitHub: