Search code examples
javaandroidaudiojavasound

automatic volume control for loud sounds played


The application im working on, plays back the sound output from device Mic in realtime to the device headphone.Application needs to automatically reduce sound levels when the sound is too loud and amplify sound levels when its too low.

    AudioTrack track = null;
    track.setStereoVolume(2.0f, 2.0f);

setStereoVolume() can change the volume levels. I can check for max amplitude from the raw PCM value and inc/dec audio volume without using FFT dynamically.Is this the right approach?To avoid lags of usingsetStreoVolume()can i not just divide the buffer values to half when the sound is too loud and multiply them to 2 when its too quiet?


Solution

  • Halving/doubling the samples at certain points would probably cause very noticeable drops/spikes in the output signal.

    What you want is a Dynamic Range Compressor. It's fairly likely that the phone already has one that runs in the platform. But if you're unhappy with its performance you can add your own software DRC. The basic idea is that you gradually attenuate the signal as it reaches a certain threshold. Since this lowers the maximum signal level (attenuates the loud parts) it allows you to add what's called a make-up gain, which will increase the overall signal level (thereby making the quiet parts louder).