MP3 Encoder (Run)¶
This article explains how you can use Transcoder.Run to encode a WAV file to MP3 (MPEG Audio Layer III) format.
The code snippets in this article are from the enc_mp3_file 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.
Initialize AVBlocks¶
The first step in any AVBlocks application is to initialize the library. This must be done before using any other AVBlocks functionality. The Library.Initialize() method sets up the internal state and loads necessary codecs. Always remember to call Library.Shutdown() at the end of your program to properly clean up resources and release any allocated memory.
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 result = Encode(opt);
Library.Shutdown();
return result ? (int)ExitCodes.Success : (int)ExitCodes.EncodingError;
}
Configure Output Socket¶
The output socket defines where and how the encoded audio data will be written. In this case, we’re configuring it to output an MP3 file. The socket represents the output destination, while the pin represents the specific audio stream within that destination. The AudioStreamInfo object specifies the audio format parameters - you can customize the bitrate, sampling rate, or number of channels by uncommenting the relevant lines.
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;
}
Configure Transcoder and Encode¶
This is the main encoding function that ties everything together. First, we create an input socket that points to the WAV file we want to encode. Then we create the output socket using our helper method. The transcoder is the core component that performs the actual encoding - it takes the uncompressed LPCM data from the input and converts it to compressed MP3 data for the output.
The AllowDemoMode = true setting allows the transcoder to work even without a valid license (useful for testing, but not recommended for production). We then add our input and output sockets to the transcoder, open it to prepare for processing, run the actual transcoding operation, and finally close it to clean up.
static bool Encode(Options opt)
{
DeleteFile(opt.OutputFile);
MediaSocket inSocket = new MediaSocket();
inSocket.File = opt.InputFile;
MediaSocket outSocket = CreateOutputSocket(opt);
// 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;
}
if (!transcoder.Run())
{
PrintError("Transcoder run", transcoder.Error);
return false;
}
transcoder.Close();
}
return true;
}
Complete C# Code¶
Here’s the complete working example that demonstrates MP3 encoding using AVBlocks. This code combines all the previous snippets into a functional program that can be compiled and run. The Main method handles command-line argument parsing, initializes AVBlocks, performs the encoding operation, and properly shuts down the library before exiting.
using System;
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 result = Encode(opt);
Library.Shutdown();
return result ? (int)ExitCodes.Success : (int)ExitCodes.EncodingError;
}
static bool Encode(Options opt)
{
DeleteFile(opt.OutputFile);
MediaSocket inSocket = new MediaSocket();
inSocket.File = opt.InputFile;
MediaSocket outSocket = CreateOutputSocket(opt);
// 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;
}
if (!transcoder.Run())
{
PrintError("Transcoder run", transcoder.Error);
return false;
}
transcoder.Close();
}
return true;
}
static void DeleteFile(string filename)
{
try
{
if (System.IO.File.Exists(filename))
System.IO.File.Delete(filename);
}
catch { }
}
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;
}
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 Windows, macOS, and Linux, and the enc_mp3_file sample for details.
Command Line¶
enc_mp3_file --input <wav file> --output <mp3 file>
Examples¶
List options:
./bin/net10.0/enc_mp3_file --help
enc_mp3_file 1.0.0.0
Copyright (C) 2023 Primo Software
-i, --input input WAV file
-o, --output output MP3 file
--help Display this help screen.
--version Display version information.
The following example encodes input file ./assets/aud/equinox-48KHz.wav into output file equinox-48KHz.mp3:
# Linux and macOS
mkdir -p ./output/enc_mp3_file
./bin/net10.0/enc_mp3_file \
--input ./assets/aud/equinox-48KHz.wav \
--output ./output/enc_mp3_file/equinox-48KHz.mp3
# Windows
mkdir -Force -Path ./output/enc_mp3_file
./bin/net10.0/enc_mp3_file `
--input ./assets/aud/equinox-48KHz.wav `
--output ./output/enc_mp3_file/equinox-48KHz.mp3