This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author alex_python_org
Recipients alex_python_org, gpolo
Date 2009-01-12.04:07:17
SpamBayes Score 0.0040133176
Marked as misclassified No
Message-id <1231733240.59.0.817430451811.issue4913@psf.upfronthosting.co.za>
In-reply-to
Content
Oh golly. I was confused. For some reason I was thinking
"writesamples()" when using "writeframes()".

So the current code reads ok. Which makes this "bug" a request for
writesamples() and readsamples() to be added to wave.py. They would
shield sleep deprived saps from the .wav file data frame format. :)


Here are python2.4-ish versions written for outside wave.py. Combos of 8
and 16 bit samples, mone and stereo, are tested. I did not test the
32-bit sample logic.

Sample values are expected to be +-32767 or +-128 ints (or +-2.x gig if
32-bit).


def readsamples(wf, nframes) :
    """ Read an array of number-of-channels normalized int sample
arrays. """

    wav = wf.readframes(nframes)

    if    wf.getsampwidth() == 4 :
        wav = struct.unpack("<%ul" % (len(wav) / 4), wav)
    elif  wf.getsampwidth() == 2 :
        wav = struct.unpack("<%uh" % (len(wav) / 2), wav)
    else :
        wav = struct.unpack("%uB"  %  len(wav),      wav)
        wav = [ s - 128 for s in wav ]

    nc  = wf.getnchannels()
    if  nc > 1  :
        wavs    = []
        for i in xrange(nc) :
            wavs.append([ wav[si] for si in xrange(0, len(wav), nc) ])
        pass
    else :
        wavs    = [ wav ]

    return(wavs)



def writesamples(wf, wavs) :
    """
        Write samples to the wave file.
        'wavs' looks like this:
               [ left_channel_samples,  right_channel_samples ]
            or [ left_channel_samples                         ]
            or   mono_samples
        This routine calls setnchannels() from information about 'wavs'
length.
    """

    if  wavs :
        if  len(wavs) not in [ 1, 2, 4 ] :
            wavs    = [ wavs, wv ]

        wf.setnchannels(len(wavs))

        if  len(wavs)   > 1 :
            wav         = []
            for w in zip(*wavs):
                wav    += w
            pass
        else :
            wav         = wavs[0]

        if    wf.getsampwidth() == 4 :
            ws  = array.array('l', [ s       for s in wav ])
        elif  wf.getsampwidth() == 2 :
            ws  = array.array('h', [ s       for s in wav ])
        else :
            ws  = array.array('B', [ s + 128 for s in wav ])

        ws  = ws.tostring()

        wf.writeframes(ws)

    pass

# end of code to edit and insert in wave.py
History
Date User Action Args
2009-01-12 04:07:21alex_python_orgsetrecipients: + alex_python_org, gpolo
2009-01-12 04:07:20alex_python_orgsetmessageid: <1231733240.59.0.817430451811.issue4913@psf.upfronthosting.co.za>
2009-01-12 04:07:19alex_python_orglinkissue4913 messages
2009-01-12 04:07:17alex_python_orgcreate