最近用python写了个计算pcm平均RMS幅度(dBfs)的脚本,其中不少小细节在此列一下 1、python没有跟C一样拿到参数个数的argc,需要使用len(sys.argv)拿到 2、seek第一个参数为offset,第二个为偏移位置 0-file start, 1-current,2-file end 3、python一个除“/”结果为浮点,即使可以整除,“//”为取整 4、‘rb’读文件拿到的数据为bytes类型,如果要转成int需要int.from_bytes方法,可以设置大小端跟有无符合。 5、浮点特定位数打印 print(“%.2f”% num); if len(sys.argv) != 2: #there is no ARGC print(“param must be 2”) exit(0) with open(sys.argv[1], ‘rb’) as fd: cnt = fd.seek(0,2)#2-seek to the end cnt = cnt//2 #use // here, other wise cnt is a float fd.seek(0,0) #0-seek to start for i in range(cnt): num = fd.read(2) num=int.from_bytes(num, byteorder=“little”, signed=“True”)# byte to int total += (num*num) dbfs=20*math.log10(math.sqrt(total/cnt)/32768)+3.013 print(“%.2f”% dbfs); #to keep 2 decimal points