Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /***********************************************************
- ** **
- ** Codesnippets written by Madwin for MMP 2023 **
- ** **
- ** Not to be used freely. the code still has errors **
- ** It's intended to be used as starting point. **
- ** Code has not been checked and might still need **
- ** a (lot of) work. **
- ** **
- ** © MadMedia Productions 2023 **
- ** **
- ***********************************************************/
- using NAudio.Wave;
- public static double GetPeakLevel(string audioFilePath)
- {
- var audioFileReader = new AudioFileReader(audioFilePath);
- // Find the highest peak sample value
- var maxSample = 0.0;
- var buffer = new float[audioFileReader.WaveFormat.SampleRate * audioFileReader.WaveFormat.Channels];
- while (audioFileReader.Read(buffer, 0, buffer.Length) > 0)
- {
- for (var i = 0; i < buffer.Length; i++)
- {
- var sample = Math.Abs(buffer[i]);
- if (sample > maxSample)
- {
- maxSample = sample;
- }
- }
- }
- // Convert the highest peak sample value to dB
- var peakLevel = 20.0 * Math.Log10(maxSample / audioFileReader.WaveFormat.SampleRate);
- return peakLevel;
- }
- /*
- To use this method, simply call GetPeakLevel with the path to your audio file. The method
- will return the peak level in dB as a double.
- */
- using NAudio.Wave;
- public static double GetPeakLevel(string audioFilePath)
- {
- var maxSample = 0.0;
- using (var audioFileReader = new WaveFileReader(audioFilePath))
- {
- var buffer = new float[audioFileReader.WaveFormat.SampleRate * audioFileReader.WaveFormat.Channels];
- var bytesRead = 0;
- do
- {
- bytesRead = audioFileReader.Read(buffer, 0, buffer.Length);
- for (var i = 0; i < bytesRead; i++)
- {
- var sample = Math.Abs(buffer[i]);
- if (sample > maxSample)
- {
- maxSample = sample;
- }
- }
- } while (bytesRead > 0);
- }
- // Convert the highest peak sample value to dB
- var peakLevel = 20.0 * Math.Log10(maxSample);
- return peakLevel;
- }
- /*
- This method uses a WaveFileReader object to read the audio file in smaller chunks instead
- of reading the entire file into memory. The WaveFileReader object is automatically disposed
- of when the using block ends, ensuring that any unmanaged resources are properly released.
- The rest of the method is the same as the previous version, converting the highest peak
- sample value to dB and returning the result as a double.
- */
Advertisement
Add Comment
Please, Sign In to add comment