Can't get a sensible result with libreplaygain.so and numpy
Question: I've been trying over and over again to use `libreplaygain.so` (`ReplayGain`
is an algorithm for calculating loudness of audio. ) from python, passing it
data from an audio file. Here is [the header
file](http://sourcecodebrowser.com/libreplaygain/1.0~r412/gain__analysis_8h_source.html)
of libreplaygain. I don't understand much about `ctypes` nor C in general, so
I'm hoping it could be a problem of me being stupid, and very obvious for
somebody else! Here is the script I am using :

    
    
    import numpy as np
    from scipy.io import wavfile
    import ctypes
    replaygain = ctypes.CDLL('libreplaygain.so')
    
    
    def calculate_replaygain(samples, frame_rate=44100):
        """
        inspired from https://github.com/vontrapp/replaygain
        """
        replaygain.gain_init_analysis(frame_rate)
        block_size = 10000
        channel_count = samples.shape[1]
        i = 0
        samples = samples.astype(np.float64)
    
        while i * block_size < samples.shape[0]:
            channel_left = samples[i*block_size:(i+1)*block_size,0]
            channel_right = samples[i*block_size:(i+1)*block_size,1]
    
            samples_p_left = channel_left.ctypes.data_as(ctypes.POINTER(ctypes.c_double))
            samples_p_right = channel_right.ctypes.data_as(ctypes.POINTER(ctypes.c_double))
    
            replaygain.gain_analyze_samples(samples_p_left, samples_p_right, channel_left.shape[0], channel_count)
            i += 1
    
        return replaygain.gain_get_chapter()
    
    
    if __name__ == '__main__':
        frame_rate, samples = wavfile.read('directions.wav')
        samples = samples.astype(np.float64) / 2**15
        gain = calculate_replaygain(samples, frame_rate=frame_rate)
        print "Recommended gain: %f dB" % gain
        gain = calculate_replaygain(np.random.random((441000, 2)) * 2 - 1, frame_rate=44100)
        print "Recommended gain: %f dB" % gain
    

The script runs, but I cannot get the same value as with the command line tool
`replaygain`. In fact I always get `80.0`. To try you can replace
'directions.wav' with any sound file ... and compare the result with the
result of the command `replaygain <soundfile.wav>`.


Answer: `gain_get_chapter()` returns a `double`, but [the ctypes docs
say](http://docs.python.org/2/library/ctypes.html#return-types) "By default
functions are assumed to return the C int type." You should do something like

    
    
    replaygain.gain_get_chapter.restype = ctypes.c_double
    

You should also check the return values of `gain_init_analysis` and
`gain_analyze_samples`; if those aren't both 1, something else is going wrong.
(Those actually are ints, so you shouldn't have to do anything else there.)

