filter mp3s by average loudness in csharp

To filter MP3s by average loudness in C#, you can use the NAudio library to read the audio data and calculate the average loudness. Here's an example code block that shows how to filter MP3s by average loudness:

main.cs
using NAudio.Wave;
using NAudio.Wave.SampleProviders;

// Define the minimum and maximum loudness values to filter by
const float minLoudness = -25.0f;
const float maxLoudness = -10.0f;

// Define a function to calculate the average loudness of the audio
float GetAverageLoudness(string filePath)
{
    var reader = new Mp3FileReader(filePath);
    var sampleProvider = reader.ToSampleProvider();
    var sampleBuffer = new float[reader.WaveFormat.SampleRate * reader.WaveFormat.Channels];
    int samplesRead = 0;
    float sum = 0;

    while ((samplesRead = sampleProvider.Read(sampleBuffer, 0, sampleBuffer.Length)) > 0)
    {
        for (int i = 0; i < samplesRead; i++)
            sum += Math.Abs(sampleBuffer[i]);
    }

    var rms = (float)Math.Sqrt(sum / sampleProvider.WaveFormat.SampleRate);
    var db = 20 * (float)Math.Log10(rms / 1);

    return db;
}

// Define a function to filter MP3s by average loudness
List<string> FilterMp3sByLoudness(string[] filePaths)
{
    var filteredFilePaths = new List<string>();

    foreach (var filePath in filePaths)
    {
        var loudness = GetAverageLoudness(filePath);

        if (loudness >= minLoudness && loudness <= maxLoudness)
            filteredFilePaths.Add(filePath);
    }

    return filteredFilePaths;
}
1280 chars
44 lines

To use this code, call the FilterMp3sByLoudness function with an array of MP3 file paths. The function will return a list of filtered file paths that have an average loudness within the specified range. Alternatively, you can modify the function to perform a more complex filtering operation.

gistlibby LogSnag