public SoxAudioNormalizer(string soxExePath, float volumeReductionDb = -3.0f)
{
if (string.IsNullOrEmpty(soxExePath))
throw new ArgumentException("SOX exe path cannot be null or empty.", nameof(soxExePath));
if (!File.Exists(soxExePath))
throw new FileNotFoundException("SOX exe not found at the specified path.", soxExePath);
_soxExePath = soxExePath;
_volumeReductionDb = volumeReductionDb;
}
/// <summary>
/// Asynchronously normalizes the audio, lowers volume slightly, applies quality improvements,
/// applies a slightly fast fadeout to the output, replaces original file.
/// </summary>
/// <param name="inputFile">Input audio file path</param>
/// <returns></returns>
public async Task NormalizeFileAsync(string inputFile)
{
if (string.IsNullOrEmpty(inputFile))
throw new ArgumentException("Input file path cannot be null or empty.", nameof(inputFile));
if (!File.Exists(inputFile))
throw new FileNotFoundException("Input audio file not found.", inputFile);
string directory = Path.GetDirectoryName(inputFile) ?? throw new InvalidOperationException("Cannot determine directory of input file.");
string fileNameWithoutExt = Path.GetFileNameWithoutExtension(inputFile);
string extension = Path.GetExtension(inputFile);
string tempOutputFile = Path.Combine(directory, fileNameWithoutExt + "_normalized" + extension);
// Apply:
// - Normalize volume by target gain (_volumeReductionDb)
// - Highpass filter at 20 Hz
// - Resample to 44100 Hz
// - Apply gain -n for dithering noise shaping
// - Apply a slightly fast fadeout of 0.3 seconds at the end of the audio
// SOX fade syntax for fade-out only:
// fade t fade-in-length [fade-out-length [fade-shape]]
// We'll set fade-in-length = 0 (no fade-in),
// fade-out-length = 0.3 (seconds),
// fade-shape = q (quarter sine), which is a smooth fade.
// Full args:
var args = $"-q \"{inputFile}\" \"{tempOutputFile}\" --norm={_volumeReductionDb} highpass 20 rate 44100 gain -n fade t 0 0 0.3 q";
await ExecuteProcessAsync(_soxExePath, args);
// After successful processing:
File.Delete(inputFile);
File.Move(tempOutputFile, inputFile);
}
private async Task ExecuteProcessAsync(string exePath, string arguments)
{
using (var process = new Process())
{
process.StartInfo.FileName = exePath;
process.StartInfo.Arguments = arguments;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
var stdOutput = string.Empty;
var stdError = string.Empty;
var tcs = new TaskCompletionSource<int>();
process.OutputDataReceived += (sender, e) =>
{
if (e.Data != null) stdOutput += e.Data + Environment.NewLine;
};
process.ErrorDataReceived += (sender, e) =>
{
if (e.Data != null) stdError += e.Data + Environment.NewLine;
};
process.EnableRaisingEvents = true;
process.Exited += (sender, e) =>
{
tcs.TrySetResult(process.ExitCode);
};
if (!process.Start())
throw new InvalidOperationException("Failed to start process.");
process.BeginOutputReadLine();
process.BeginErrorReadLine();
int exitCode = await tcs.Task.ConfigureAwait(false);
if (exitCode != 0)
{
throw new InvalidOperationException(
$"SOX process failed with exit code {exitCode}.\nStdOut: {stdOutput}\nStdErr: {stdError}");
}
}
}