#!/usr/bin/python #run the app and spawn a thread when you need to commit something to mysql import ossaudiodev import struct import time import ogg import ogg.vorbis import array import os import MySQLdb import popen2 from threading import Thread class saveAudioStream(Thread): def __init__(self,timeHeard,recSamples,sampleRate): Thread.__init__(self) self.sampleRate=sampleRate self.recSamples=recSamples self.timeHeard=timeHeard def run(self): self.record="".join(self.recSamples) filename="/tmp/temp-"+str(self.timeHeard)+".raw" child = popen2.Popen3("lame -x --resample 12 -b 16 -s 44.1 -m m - "+filename) print "PID: ", child.pid child.tochild.write(self.record) child.tochild.close() child.wait() mp3Sample=child.fromchild.read() child.fromchild.close() mp3file=open(filename,"rb") mp3Sample=mp3file.read() mp3file.close() os.unlink(filename) print "Was "+str(len(self.record))+" enc it is "+str(len(mp3Sample)) db=MySQLdb.connect(passwd="",db="scanner",host="localhost",user="root") c=db.cursor() c.execute("INSERT INTO samples (endtime, starttime, mp3sample ) VALUES (NOW(),%s,%s)", (self.timeHeard,mp3Sample,)) db.close() print "---------------------------" number_of_channels= 1 sample_rate=44100 sample_len=1000 heardSomething=0 timeHeard=0 threshold=50 recSamples=[] audio_in= ossaudiodev.open("/dev/dsp", "r") audio_in.setparameters(ossaudiodev.AFMT_S16_LE, number_of_channels,sample_rate) print "Sample rate at "+str(sample_len) while 1: frames_in= audio_in.read(sample_len) try: average = sum(struct.unpack(str((sample_len/2))+'h',frames_in))/(sample_len/2) except: average=0 #if we can hear something.. if average > threshold: if heardSomething==0: heardSomething=1 startHeard=time.time() print "Im hearin somethin...sssh" timeHeard=time.time() if average < threshold : if heardSomething==1 and (time.time()-timeHeard) >1.5 and timeHeard >0: print "\t completed at "+str(timeHeard)+" len: "+str(time.time()-startHeard) recWriter=saveAudioStream(startHeard,recSamples,sample_rate) heardSomething=0 timeHeard=0 recWriter.start() recSamples=[] if heardSomething==1: recSamples.append(frames_in)