How to configure output socket for MP3 encoding in C++#

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

Diagram#

The Transcoder with an input MediaSocket and an output MediaSocket. The input MediaSocket only has a file. The output MediaSocket has a Pins connector that a MediaPin plugs into; the MediaPin holds an AudioStreamInfo with the StreamType and StreamSubType of the MP3 stream. The Transcoder with an input MediaSocket and an output MediaSocket. The input MediaSocket only has a file. The output MediaSocket has a Pins connector that a MediaPin plugs into; the MediaPin holds an AudioStreamInfo with the StreamType and StreamSubType of the MP3 stream.

Code#

This is the code for the output socket:

primo::ref<MediaSocket> createOutputSocket(Options& opt)
{
    // create stream info to describe the output audio stream
    auto asi = primo::make_ref(Library::createAudioStreamInfo());
    asi->setStreamType(StreamType::MPEG_Audio);
    asi->setStreamSubType(StreamSubType::MPEG_Audio_Layer3);

    // The default bitrate is 128000. You can set it to 192000, 256000, etc.
    // asi->setBitrate(192000);

    // Optionally set the sampling rate and the number of the channels, e.g. 44.1 Khz, Mono 
    // asi->setSampleRate(44100);
    // asi->setChannels(1);

    // create a pin using the stream info 
    auto pin = primo::make_ref(Library::createMediaPin());
    pin->setStreamInfo(asi.get());

    // the pin allows you to specify additional parameters for the encoder 
    // for example, change the stereo mode, e.g. Joint Stereo
    // pin->params()->addInt(Param::Encoder::Audio::MPEG1::StereoMode, StereoMode::Joint);

    // finally create a socket for the output container format which is MP3 in this case
    auto socket = primo::make_ref(Library::createMediaSocket());
    socket->setStreamType(StreamType::MPEG_Audio);
    socket->setStreamSubType(StreamSubType::MPEG_Audio_Layer3);

    socket->pins()->add(pin.get());

    // output to a file
    auto output_file = primo::ustring(opt.outputFile);
    socket->setFile(output_file);

    return socket;
}

The complete program is available on GitHub:

Comments

comments powered by Disqus