'Transform a numpy array to a PCM bytestring'

def _make_wav(self, data, rate):

    import struct
    from io import BytesIO
    import wave
    try:
        import numpy as np
        data = np.array(data, dtype=float)
        if (len(data.shape) == 1):
            nchan = 1
        elif (len(data.shape) == 2):
            nchan = data.shape[0]
            data = data.T.ravel()
        else:
            raise ValueError('Array    audio    input    must    be    a    1D    or    2D    array')
        scaled = np.int16(((data / np.max(np.abs(data))) * 32767)).tolist()
    except ImportError:
        idata = iter(data)
        try:
            iter(idata.next())
            raise TypeError('Only    lists    of    mono    audio    are    supported    if    numpy    is    not    installed')
        except TypeError:
            pass
        maxabsvalue = float(max([abs(x) for x in data]))
        scaled = [int(((x / maxabsvalue) * 32767)) for x in data]
        nchan = 1
    fp = BytesIO()
    waveobj = wave.open(fp, mode='wb')
    waveobj.setnchannels(nchan)
    waveobj.setframerate(rate)
    waveobj.setsampwidth(2)
    waveobj.setcomptype('NONE', 'NONE')
    waveobj.writeframes(''.join([struct.pack('<h', x) for x in scaled]))
    val = fp.getvalue()
    waveobj.close()
    return val
