#!/usr/bin/python

# clip_from_wave.py
#       --copyright--                   Copyright 2007 (C) Tranzoa, Co. All rights reserved.    Warranty: You're free and on your own here. This code is not necessarily up-to-date or of public quality.
#       --url--                         http://www.tranzoa.net/tzpython/
#       --email--                       pycode is the name to send to. tranzoa.com is the place to send to.
#       --bodstamps--
#       February 4, 2005        bar
#       November 18, 2007       bar     turn on doxygen
#       November 27, 2007       bar     insert boilerplate copyright
#       May 17, 2008            bar     email adr
#       --eodstamps--
##      \file
#
#
#       Create a "clip" file from a .wav file.
#
#


__ALL__ = [
            'clip_from_wave',
          ]



def clip_from_wave(wav_file_samples, wav_file_params, clip_duration = None, clip_start = None) :

    if  clip_duration == None : clip_duration = 30
    if  clip_start    == None : clip_start    = 0.666666666666666

    #         stereo=2     16=2 8=1 sps=44100
    bp_smp  = wp[0]      * wp[1]
    cd      = int(int(int(bp_smp * wp[2] * clip_duration) / bp_smp) * bp_smp)

    cs  = int(int(int(len(wav_file_samples) * clip_start) / bp_smp) * bp_smp)
    es  = len(wav_file_samples) - cd
    if  cs > es :
        cs = es

    if  cs >= 0 :
        cs  = int(int(cs / bp_smp) * bp_smp)
    else :
        cs = 0
        cd = len(wav_file_samples)

    return(wav_file_samples[cs:cs + cd])




if  __name__ == '__main__' :
    import  sys
    import  wave

    if  len(sys.argv) < 2 :
        print "Tell me input and output .wav file names."
        sys.exit(1)

    ifile_name = sys.argv[1]
    ofile_name = sys.argv[2]

    fi = wave.open(ifile_name, "rb")

    wp      = fi.getparams()

    wav     = fi.readframes(fi.getnframes())

    fi.close()

    cd  = None
    if  len(sys.argv) > 3 :
        cd  = float(sys.argv[3])

    wav     = clip_from_wave(wav, wp, cd)


    fo      = wave.open(ofile_name, "wb")

    fo.setparams(wp)

    fo.writeframes(wav)

    fo.close()

    pass

#
#
#
# eof
