from pathlib import Path
import wave,array,math,json
base=Path('/tmp/erri-welcome-audio')
def envelope(path):
 with wave.open(str(path),'rb') as w:
  assert w.getsampwidth()==2 and w.getnchannels()==1
  rate=w.getframerate();a=array.array('h',w.readframes(w.getnframes()));block=rate//100
  return [math.sqrt(sum(v*v for v in a[i:i+block])/block) for i in range(0,len(a)-block,block)]
s=envelope(base/'welcome.wav');c=envelope(base/'mission-native3/capture.wav')
def corr(a,b):
 am=sum(a)/len(a);bm=sum(b)/len(b);aa=[x-am for x in a];bb=[x-bm for x in b]
 return sum(x*y for x,y in zip(aa,bb))/math.sqrt(max(1,sum(x*x for x in aa)*sum(x*x for x in bb)))
best=max((corr(s,c[i:i+len(s)]),i) for i in range(len(c)-len(s)))
result={'envelope_correlation':best[0],'capture_offset_seconds':best[1]/100,'matched_seconds':len(s)/100}
(base/'mission-native3/audio-match.json').write_text(json.dumps(result,indent=2));print(result)
