#!/usr/bin/python2
#
# Ecarecord.py
#
# Use ecasound to record an audio .wav file.
# Stop when the user types Control-C.
# If a wav file name is not given on the command line, generate
# a unique file name based on the date and time.
#
# G. Forrest Cook
# January 15, 2003
# April 30, 2003 improved the command line argument handling,
# added sample rate option.
#

import getopt
import sys
import os

def usage ():
    print 'usage: %s [-f wav_file] [-r sample rate]' %(sys.argv[0])
    return

#
# The main code starts here.
#
ecasound = "/usr/local/bin/ecasound"
rm_cmd = "/bin/rm"
date_cmd = "/bin/date"

# Create a wav file name based on the date.
datepipe = os.popen (date_cmd + " +%Y-%m-%d@%H:%M:%S")
date_line = datepipe.readline ()
date_line = date_line[0:len(date_line)-1]
datepipe.close ()
wav_file = date_line + ".wav"

# Default sample rate
samp_rate = 44100

try:
    opts, args = getopt.getopt(sys.argv[1:], "f:r:h")
except getopt.GetoptError:
    usage()
    sys.exit(2)

for o, a in opts:
    if o == "-r":
	samp_rate = a
    if o == "-f":
	wav_file = a
    if o == "-h":
	usage()
	sys.exit(2)

if len(args) > 0:
    usage()
    sys.exit(2)

print "Wav File Name:", wav_file
print "Sample Rate:", samp_rate

#
# Remove the old wav file if it's already there.
#
os.system (rm_cmd + " -f " + wav_file)
    
#
# Run the recording command.
#
comd = ecasound+" -r -f:16,2,"+str(samp_rate)+" -i /dev/dsp -o "+wav_file
print comd

# This exits when the user types Control-C
os.system (comd)

sys.exit (0)
