"""Routines to help recognizing sound files.Function whathdr() recognizes various types of sound file headers.It understands almost all headers that SOX can decode.The return tuple contains the following items, in this order:- file type (as SOX understands it)- sampling rate (0 if unknown or hard to decode)- number of channels (0 if unknown or hard to decode)- number of frames in the file (-1 if unknown or hard to decode)- number of bits/sample, or 'U' for U-LAW, or 'A' for A-LAWIf the file doesn't have a recognizable type, it returns None.If the file can't be opened, IOError is raised.To compute the total time, divide the number of frames by thesampling rate (a frame contains a sample for each channel).Function what() calls whathdr(). (It used to also use someheuristics for raw data, but this doesn't work very well.)Finally, the function test() is a simple main program that callswhat() for all files mentioned on the argument list. For directoryarguments it calls what() for all files in that directory. Defaultargument is "." (testing all files in the current directory). Theoption -r tells it to recurse down directories found insideexplicitly given directories."""# The file structure is top-down except that the test program and its# subroutine come last.__all__=["what","whathdr"]defwhat(filename):"""Guess the type of a sound file"""res=whathdr(filename)returnresdefwhathdr(filename):"""Recognize sound headers"""f=open(filename,'rb')h=f.read(512)fortfintests:res=tf(h,f)ifres:returnresreturnNone#-----------------------------------## Subroutines per sound header type ##-----------------------------------#tests=[]deftest_aifc(h,f):importaifcifh[:4]!='FORM':returnNoneifh[8:12]=='AIFC':fmt='aifc'elifh[8:12]=='AIFF':fmt='aiff'else:returnNonef.seek(0)try:a=aifc.openfp(f,'r')except(EOFError,aifc.Error):returnNonereturn(fmt,a.getframerate(),a.getnchannels(), \
a.getnframes(),8*a.getsampwidth())tests.append(test_aifc)deftest_au(h,f):ifh[:4]=='.snd':f=get_long_beelifh[:4]in('\0ds.','dns.'):f=get_long_leelse:returnNonetype='au'hdr_size=f(h[4:8])data_size=f(h[8:12])encoding=f(h[12:16])rate=f(h[16:20])nchannels=f(h[20:24])sample_size=1# defaultifencoding==1:sample_bits='U'elifencoding==2:sample_bits=8elifencoding==3:sample_bits=16sample_size=2else:sample_bits='?'frame_size=sample_size*nchannelsreturntype,rate,nchannels,data_size/frame_size,sample_bitstests.append(test_au)deftest_hcom(h,f):ifh[65:69]!='FSSD'orh[128:132]!='HCOM':returnNonedivisor=get_long_be(h[128+16:128+20])return'hcom',22050/divisor,1,-1,8tests.append(test_hcom)deftest_voc(h,f):ifh[:20]!='Creative Voice File\032':returnNonesbseek=get_short_le(h[20:22])rate=0if0<=sbseek<500andh[sbseek]=='\1':ratecode=ord(h[sbseek+4])rate=int(1000000.0/(256-ratecode))return'voc',rate,1,-1,8tests.append(test_voc)deftest_wav(h,f):# 'RIFF' <len> 'WAVE' 'fmt ' <len>ifh[:4]!='RIFF'orh[8:12]!='WAVE'orh[12:16]!='fmt ':returnNonestyle=get_short_le(h[20:22])nchannels=get_short_le(h[22:24])rate=get_long_le(h[24:28])sample_bits=get_short_le(h[34:36])return'wav',rate,nchannels,-1,sample_bitstests.append(test_wav)deftest_8svx(h,f):ifh[:4]!='FORM'orh[8:12]!='8SVX':returnNone# Should decode it to get #channels -- assume always 1return'8svx',0,1,0,8tests.append(test_8svx)deftest_sndt(h,f):ifh[:5]=='SOUND':nsamples=get_long_le(h[8:12])rate=get_short_le(h[20:22])return'sndt',rate,1,nsamples,8tests.append(test_sndt)deftest_sndr(h,f):ifh[:2]=='\0\0':rate=get_short_le(h[2:4])if4000<=rate<=25000:return'sndr',rate,1,-1,8tests.append(test_sndr)#---------------------------------------------## Subroutines to extract numbers from strings ##---------------------------------------------#defget_long_be(s):return(ord(s[0])<<24)|(ord(s[1])<<16)|(ord(s[2])<<8)|ord(s[3])defget_long_le(s):return(ord(s[3])<<24)|(ord(s[2])<<16)|(ord(s[1])<<8)|ord(s[0])defget_short_be(s):return(ord(s[0])<<8)|ord(s[1])defget_short_le(s):return(ord(s[1])<<8)|ord(s[0])#--------------------## Small test program ##--------------------#deftest():importsysrecursive=0ifsys.argv[1:]andsys.argv[1]=='-r':delsys.argv[1:2]recursive=1try:ifsys.argv[1:]:testall(sys.argv[1:],recursive,1)else:testall(['.'],recursive,1)exceptKeyboardInterrupt:sys.stderr.write('\n[Interrupted]\n')sys.exit(1)deftestall(list,recursive,toplevel):importsysimportosforfilenameinlist:ifos.path.isdir(filename):printfilename+'/:',ifrecursiveortoplevel:print'recursing down:'importglobnames=glob.glob(os.path.join(filename,'*'))testall(names,recursive,0)else:print'*** directory (use -r) ***'else:printfilename+':',sys.stdout.flush()try:printwhat(filename)exceptIOError:print'*** not found ***'if__name__=='__main__':test()