Class AudioUtility

java.lang.Object
net.paulhertz.pixelaudio.schedule.AudioUtility

public final class AudioUtility extends Object
Utility conversions for audio.
  • Nested Class Summary

    Nested Classes
    Modifier and Type
    Class
    Description
    (package private) static enum 
    Strategies for adjusting signal level.
  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    private static final double
    Precomputed log(2) for efficiency.
    static final double
    Constant: 2^(1/12), the ratio of one semitone.
  • Constructor Summary

    Constructors
    Modifier
    Constructor
    Description
    private
     
  • Method Summary

    Modifier and Type
    Method
    Description
    static float
    computeDCOffset(float[] signal)
    Computes the average sample value, useful for detecting DC offset.
    static float
    computePeak(float[] signal)
    Computes the peak absolute sample value of a signal.
    static float
    computePeak(ddf.minim.MultiChannelBuffer buffer)
    Computes the peak absolute sample value across all channels in a Minim buffer.
    static float
    computeRMS(float[] signal)
    Computes the RMS (root mean square) level of a signal.
    static float
    computeRMS(ddf.minim.MultiChannelBuffer buffer)
    Computes RMS across all channels in a Minim buffer.
    static float
    conditionForOutput(float[] signal, float ceilingDB, float drive, boolean removeDC)
    Applies a conservative output-conditioning chain: optional DC removal, peak protection, optional soft limiting, and a final hard safety clip.
    static float
    conditionForOutput(ddf.minim.MultiChannelBuffer buffer, float ceilingDB, float drive, boolean removeDC)
    Applies a conservative output-conditioning chain to every channel in a Minim buffer.
    static int
    countOverloads(float[] signal, float ceiling)
    Counts samples whose absolute value exceeds a ceiling.
    static int
    countOverloads(ddf.minim.MultiChannelBuffer buffer, float ceiling)
    Counts samples whose absolute value exceeds a ceiling across all channels.
    static float
    dbToLinear(float dB)
    Converts a gain value in decibels (dB) to a linear amplitude multiplier.
    static int
    fileSamplesRequiredForDisplay(int mapSize, float fileSampleRate, float audioOutRate)
    Computes how many source-file samples are needed to fill a display map at output rate.
    static float
    frequencyPianoKey(float freq)
    Convert frequency to fractional MIDI-style key number.
    static int
    hardClip(float[] signal, float ceiling)
    Hard-clips a signal to an absolute ceiling.
    static int
    hardClip(ddf.minim.MultiChannelBuffer buffer, float ceiling)
    Hard-clips every channel in a Minim buffer to an absolute ceiling.
    static float
    linearToDb(float linear)
     
    static long
    millisToSamples(double millis, double sampleRate)
    Converts milliseconds to the nearest sample count.
    static void
    normalizePeakDb(float[] signal, float targetPeakDB)
    Normalizes a signal so its peak reaches a target dBFS value.
    static void
    normalizePeakLevel(float[] signal, float targetPeakLevel)
    Normalizes a signal so its peak reaches a target linear level.
    static float
    normalizeRMS(float[] signal, float targetDB)
    Normalizes a single-channel signal array to a target RMS level in dBFS.
    static void
    normalizeRmsWithCeiling(float[] signal, float targetRmsDB, float peakCeilingDB)
    Normalizes toward a target RMS level while limiting the applied gain by a peak ceiling.
    static float
    pianoKeyFrequency(float keyNumber)
    Convert MIDI-style key number to frequency (A4 = 440 Hz, key 49).
    static float
    protectPeak(float[] signal, float ceiling)
    Reduces gain only when a signal peak exceeds the requested ceiling.
    static float
    protectPeak(ddf.minim.MultiChannelBuffer buffer, float ceiling)
    Reduces gain across all channels only when a buffer peak exceeds the requested ceiling.
    static float
    ratioToSemitones(float ratio)
    Convert frequency ratio to semitone offset.
    static float
    removeDCOffset(float[] signal)
    Removes DC offset from a signal by subtracting its average sample value.
    static void
    removeDCOffset(ddf.minim.MultiChannelBuffer buffer)
    Removes DC offset independently from each channel in a Minim buffer.
    static ddf.minim.MultiChannelBuffer
    resampleMCB(ddf.minim.MultiChannelBuffer src, float sourceRate, float targetRate)
    Resamples all channels in a MultiChannelBuffer from sourceRate to targetRate.
    static ddf.minim.MultiChannelBuffer
    resampleMCBToOutput(ddf.minim.MultiChannelBuffer src, float sourceRate, ddf.minim.AudioOutput out)
    Convenience: resample MultiChannelBuffer from sourceRate to match AudioOutput.
    static float[]
    resampleMono(float[] source, float sourceRate, float targetRate)
    Resamples a mono buffer from sourceRate to targetRate using linear interpolation.
    static float[]
    resampleMonoToOutput(float[] source, float sourceRate, ddf.minim.AudioOutput out)
    Convenience: resample mono buffer from sourceRate to match AudioOutput sample rate.
    static double
    samplesToMillis(long samples, double sampleRate)
    Converts a sample count to milliseconds.
    static void
    saveAudioTo32BitPCMFile(float[] samples, float sampleRate, String fileName)
    Saves audio data to a 32-bit floating point format that has higher resolution than 16-bit integer PCM.
    static void
    saveAudioToFile(float[] samples, float sampleRate, String fileName)
    Saves audio data to 16-bit integer PCM format, which Processing can also open.
    static void
    saveStereoAudioTo32BitPCMFile(float[] leftChannel, float[] rightChannel, float sampleRate, String fileName)
    Saves stereo audio data to a 32-bit floating point format that has higher resolution than 16-bit integer PCM.
    static void
    saveStereoAudioToFile(float[] leftChannel, float[] rightChannel, float sampleRate, String fileName)
    Saves stereo audio data to 16-bit integer PCM format, which Processing can also open.
    static long
    secsToSamples(double secs, double sampleRate)
    Converts seconds to the nearest sample count.
    static float
    semitonesToRatio(float semitones)
    Convert semitone offset to frequency ratio.
    static float
    softClipSoftsign(float sample, float drive)
    Softsign limiting curve used by the sampler mix protection path.
    static void
    softLimitSoftsign(float[] signal, float drive)
    Applies softsign limiting to a signal in place.
    static void
    softLimitSoftsign(ddf.minim.MultiChannelBuffer buffer, float drive)
    Applies softsign limiting independently to every channel in a Minim buffer.
    static float
    transposeFrequency(float freq, float semitones)
    Apply a semitone offset directly to a frequency.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Field Details

    • SEMITONE_FAC

      public static final double SEMITONE_FAC
      Constant: 2^(1/12), the ratio of one semitone.
    • LOG2

      private static final double LOG2
      Precomputed log(2) for efficiency.
  • Constructor Details

    • AudioUtility

      private AudioUtility()
  • Method Details

    • millisToSamples

      public static long millisToSamples(double millis, double sampleRate)
      Converts milliseconds to the nearest sample count.
      Parameters:
      millis - duration in milliseconds
      sampleRate - sample rate in Hz
      Returns:
      sample count rounded to nearest integer
    • samplesToMillis

      public static double samplesToMillis(long samples, double sampleRate)
      Converts a sample count to milliseconds.
      Parameters:
      samples - sample count
      sampleRate - sample rate in Hz
      Returns:
      duration in milliseconds
    • secsToSamples

      public static long secsToSamples(double secs, double sampleRate)
      Converts seconds to the nearest sample count.
      Parameters:
      secs - duration in seconds
      sampleRate - sample rate in Hz
      Returns:
      sample count rounded to nearest integer
    • dbToLinear

      public static float dbToLinear(float dB)
      Converts a gain value in decibels (dB) to a linear amplitude multiplier.
        0.0 dB  -> 1.0
       -6.0 dB  -> ~0.501
       +6.0 dB  -> ~1.995
       
      Parameters:
      dB - gain in decibels
      Returns:
      linear gain multiplier
    • linearToDb

      public static float linearToDb(float linear)
      Parameters:
      linear - decimal gain value, for example from a UI slider
      Returns:
      values in decibels for linear
    • semitonesToRatio

      public static float semitonesToRatio(float semitones)
      Convert semitone offset to frequency ratio.
      Parameters:
      semitones - number of semitones (can be fractional)
      Returns:
      frequency ratio (>0)
       Examples:
         12  -> 2.0
          0  -> 1.0
        -12  -> 0.5
       
    • ratioToSemitones

      public static float ratioToSemitones(float ratio)
      Convert frequency ratio to semitone offset.
      Parameters:
      ratio - frequency ratio (>0)
      Returns:
      semitone offset (can be fractional)
    • pianoKeyFrequency

      public static float pianoKeyFrequency(float keyNumber)
      Convert MIDI-style key number to frequency (A4 = 440 Hz, key 49).
      Parameters:
      keyNumber - MIDI-style key number, where A4 is 49
      Returns:
      frequency in Hz
    • frequencyPianoKey

      public static float frequencyPianoKey(float freq)
      Convert frequency to fractional MIDI-style key number.
      Parameters:
      freq - frequency in Hz
      Returns:
      fractional MIDI-style key number
    • transposeFrequency

      public static float transposeFrequency(float freq, float semitones)
      Apply a semitone offset directly to a frequency.
      Parameters:
      freq - source frequency in Hz
      semitones - transposition amount in semitones
      Returns:
      transposed frequency in Hz
    • computePeak

      public static float computePeak(float[] signal)
      Computes the peak absolute sample value of a signal.
      Parameters:
      signal - the audio samples
      Returns:
      Maximum absolute sample value (linear scale)
    • computeRMS

      public static float computeRMS(float[] signal)
      Computes the RMS (root mean square) level of a signal.
      Parameters:
      signal - the audio samples
      Returns:
      RMS value (linear scale)
    • computePeak

      public static float computePeak(ddf.minim.MultiChannelBuffer buffer)
      Computes the peak absolute sample value across all channels in a Minim buffer.
      Parameters:
      buffer - audio buffer
      Returns:
      maximum absolute sample value across all channels
    • computeRMS

      public static float computeRMS(ddf.minim.MultiChannelBuffer buffer)
      Computes RMS across all channels in a Minim buffer.
      Parameters:
      buffer - audio buffer
      Returns:
      RMS value across all samples in all channels
    • computeDCOffset

      public static float computeDCOffset(float[] signal)
      Computes the average sample value, useful for detecting DC offset.
      Parameters:
      signal - audio samples
      Returns:
      mean sample value
    • removeDCOffset

      public static float removeDCOffset(float[] signal)
      Removes DC offset from a signal by subtracting its average sample value.
      Parameters:
      signal - audio samples to modify in place
      Returns:
      offset that was subtracted
    • removeDCOffset

      public static void removeDCOffset(ddf.minim.MultiChannelBuffer buffer)
      Removes DC offset independently from each channel in a Minim buffer.
      Parameters:
      buffer - audio buffer to modify in place
    • countOverloads

      public static int countOverloads(float[] signal, float ceiling)
      Counts samples whose absolute value exceeds a ceiling.
      Parameters:
      signal - audio samples
      ceiling - positive absolute ceiling
      Returns:
      number of samples above the ceiling
    • countOverloads

      public static int countOverloads(ddf.minim.MultiChannelBuffer buffer, float ceiling)
      Counts samples whose absolute value exceeds a ceiling across all channels.
      Parameters:
      buffer - audio buffer
      ceiling - positive absolute ceiling
      Returns:
      number of samples above the ceiling
    • hardClip

      public static int hardClip(float[] signal, float ceiling)
      Hard-clips a signal to an absolute ceiling.
      Parameters:
      signal - audio samples to modify in place
      ceiling - positive absolute ceiling
      Returns:
      number of samples that were clipped
    • hardClip

      public static int hardClip(ddf.minim.MultiChannelBuffer buffer, float ceiling)
      Hard-clips every channel in a Minim buffer to an absolute ceiling.
      Parameters:
      buffer - audio buffer to modify in place
      ceiling - positive absolute ceiling
      Returns:
      number of samples that were clipped
    • softClipSoftsign

      public static float softClipSoftsign(float sample, float drive)
      Softsign limiting curve used by the sampler mix protection path.
      Parameters:
      sample - input sample
      drive - positive pre-limiter drive; values <= 0 return the input sample unchanged
      Returns:
      softly limited sample in the interval (-1, 1)
    • softLimitSoftsign

      public static void softLimitSoftsign(float[] signal, float drive)
      Applies softsign limiting to a signal in place.
      Parameters:
      signal - audio samples to modify in place
      drive - positive pre-limiter drive
    • softLimitSoftsign

      public static void softLimitSoftsign(ddf.minim.MultiChannelBuffer buffer, float drive)
      Applies softsign limiting independently to every channel in a Minim buffer.
      Parameters:
      buffer - audio buffer to modify in place
      drive - positive pre-limiter drive
    • protectPeak

      public static float protectPeak(float[] signal, float ceiling)
      Reduces gain only when a signal peak exceeds the requested ceiling.
      Parameters:
      signal - audio samples to modify in place
      ceiling - positive absolute ceiling
      Returns:
      gain applied to the signal, or 1.0 when no reduction was needed
    • protectPeak

      public static float protectPeak(ddf.minim.MultiChannelBuffer buffer, float ceiling)
      Reduces gain across all channels only when a buffer peak exceeds the requested ceiling.
      Parameters:
      buffer - audio buffer to modify in place
      ceiling - positive absolute ceiling
      Returns:
      gain applied to every channel, or 1.0 when no reduction was needed
    • conditionForOutput

      public static float conditionForOutput(float[] signal, float ceilingDB, float drive, boolean removeDC)
      Applies a conservative output-conditioning chain: optional DC removal, peak protection, optional soft limiting, and a final hard safety clip.

      Calling AudioUtility.conditionForOutput(signal, -1.0f, 1.5f, true) will 1) remove DC offset, 2) reduce overal gain if the peak is above -1 dBFS, 3) apply softsign limiting with moderate drive, 4) hard-clip as a final safety guard.

      Parameters:
      signal - audio samples to modify in place
      ceilingDB - peak ceiling in dBFS
      drive - soft limiter drive; values <= 0 skip soft limiting
      removeDC - true to remove DC offset before limiting
      Returns:
      gain applied during peak protection
    • conditionForOutput

      public static float conditionForOutput(ddf.minim.MultiChannelBuffer buffer, float ceilingDB, float drive, boolean removeDC)
      Applies a conservative output-conditioning chain to every channel in a Minim buffer.

      Calling AudioUtility.conditionForOutput(buffer, -1.0f, 1.5f, true) will 1) remove DC offset, 2) reduce overal gain if the peak is above -1 dBFS, 3) apply softsign limiting with moderate drive, 4) hard-clip as a final safety guard.

      Parameters:
      buffer - audio buffer to modify in place
      ceilingDB - peak ceiling in dBFS
      drive - soft limiter drive; values <= 0 skip soft limiting
      removeDC - true to remove DC offset before limiting
      Returns:
      gain applied during peak protection
    • normalizeRMS

      public static float normalizeRMS(float[] signal, float targetDB)
      Normalizes a single-channel signal array to a target RMS level in dBFS.
      Parameters:
      signal - the audio samples to normalize (modified in place)
      targetDB - the peak level in dB (e.g. -3.0f for moderately loud, -12.0f for safe headroom)
      Returns:
      gain applied to signal
    • normalizePeakDb

      public static void normalizePeakDb(float[] signal, float targetPeakDB)
      Normalizes a signal so its peak reaches a target dBFS value.
      Parameters:
      signal - audio samples to modify in place
      targetPeakDB - target peak level in dBFS
    • normalizePeakLevel

      public static void normalizePeakLevel(float[] signal, float targetPeakLevel)
      Normalizes a signal so its peak reaches a target linear level.
      Parameters:
      signal - audio samples to modify in place
      targetPeakLevel - target peak level on a linear scale
    • normalizeRmsWithCeiling

      public static void normalizeRmsWithCeiling(float[] signal, float targetRmsDB, float peakCeilingDB)
      Normalizes toward a target RMS level while limiting the applied gain by a peak ceiling.
      Parameters:
      signal - audio samples to modify in place
      targetRmsDB - target RMS level in dBFS
      peakCeilingDB - maximum permitted peak level in dBFS
    • fileSamplesRequiredForDisplay

      public static int fileSamplesRequiredForDisplay(int mapSize, float fileSampleRate, float audioOutRate)
      Computes how many source-file samples are needed to fill a display map at output rate.
      Parameters:
      mapSize - number of display/audio output samples
      fileSampleRate - sample rate of the source audio file
      audioOutRate - sample rate of the audio output
      Returns:
      required source sample count, rounded up
    • resampleMono

      public static float[] resampleMono(float[] source, float sourceRate, float targetRate)
      Resamples a mono buffer from sourceRate to targetRate using linear interpolation.
      Parameters:
      source - mono samples at sourceRate
      sourceRate - sample rate of the source buffer (Hz)
      targetRate - desired sample rate (Hz)
      Returns:
      new float[] at targetRate
    • resampleMonoToOutput

      public static float[] resampleMonoToOutput(float[] source, float sourceRate, ddf.minim.AudioOutput out)
      Convenience: resample mono buffer from sourceRate to match AudioOutput sample rate.
      Parameters:
      source - mono samples at sourceRate
      sourceRate - sample rate of the source buffer (Hz)
      out - target AudioOutput
      Returns:
      new mono buffer at the output sample rate
    • resampleMCB

      public static ddf.minim.MultiChannelBuffer resampleMCB(ddf.minim.MultiChannelBuffer src, float sourceRate, float targetRate)
      Resamples all channels in a MultiChannelBuffer from sourceRate to targetRate. Produces a new MultiChannelBuffer at targetRate. For PixelAudio you may only need channel 0 (mono); this is available mainly for completeness.
      Parameters:
      src - source buffer to resample
      sourceRate - sample rate of the source buffer (Hz)
      targetRate - desired sample rate (Hz)
      Returns:
      new buffer at targetRate
    • resampleMCBToOutput

      public static ddf.minim.MultiChannelBuffer resampleMCBToOutput(ddf.minim.MultiChannelBuffer src, float sourceRate, ddf.minim.AudioOutput out)
      Convenience: resample MultiChannelBuffer from sourceRate to match AudioOutput.
      Parameters:
      src - source buffer to resample
      sourceRate - sample rate of the source buffer (Hz)
      out - target AudioOutput
      Returns:
      new buffer at the output sample rate
    • saveAudioToFile

      public static void saveAudioToFile(float[] samples, float sampleRate, String fileName) throws IOException, UnsupportedAudioFileException
      Saves audio data to 16-bit integer PCM format, which Processing can also open.
      Parameters:
      samples - an array of floats in the audio range (-1.0f, 1.0f)
      sampleRate - audio sample rate for the file
      fileName - name of the file to save to
      Throws:
      IOException - an Exception you'll need to handle to call this method (see keyPressed entry for 's')
      UnsupportedAudioFileException
    • saveAudioTo32BitPCMFile

      public static void saveAudioTo32BitPCMFile(float[] samples, float sampleRate, String fileName) throws IOException
      Saves audio data to a 32-bit floating point format that has higher resolution than 16-bit integer PCM. The format can't be opened by Processing but can be opened by audio applications.
      Parameters:
      samples - an array of floats in the audio range (-1.0f, 1.0f)
      sampleRate - the sample rate for the file
      fileName - name of the file
      Throws:
      IOException - an Exception you'll need to catch to call this method (see keyPressed entry for 's')
    • saveStereoAudioToFile

      public static void saveStereoAudioToFile(float[] leftChannel, float[] rightChannel, float sampleRate, String fileName) throws IOException, UnsupportedAudioFileException
      Saves stereo audio data to 16-bit integer PCM format, which Processing can also open.
      Parameters:
      leftChannel - an array of floats in the audio range (-1.0f, 1.0f)
      rightChannel - an array of floats in the audio range (-1.0f, 1.0f)
      sampleRate - audio sample rate for the file
      fileName - name of the file to save to
      Throws:
      IOException - an Exception you'll need to handle to call this method (see keyPressed entry for 's')
      UnsupportedAudioFileException
    • saveStereoAudioTo32BitPCMFile

      public static void saveStereoAudioTo32BitPCMFile(float[] leftChannel, float[] rightChannel, float sampleRate, String fileName) throws IOException
      Saves stereo audio data to a 32-bit floating point format that has higher resolution than 16-bit integer PCM. The format can't be opened by Processing but can be opened by audio applications.
      Parameters:
      leftChannel - an array of floats in the audio range (-1.0f, 1.0f)
      rightChannel - an array of floats in the audio range (-1.0f, 1.0f)
      sampleRate - the sample rate for the file
      fileName - name of the file
      Throws:
      IOException