import wave as wv
import numpy as np
import matplotlib.pyplot as plt
from scipy.io.wavfile import read
#import used libraries
#function that converts .WAV file to np_array
def MakeArray(file):
# Read in file
ifile = wave.open(file)
samples = ifile.getnframes()
audio = ifile.readframes(samples)
# Conversion to float32
audio_as_np_int16 = np.frombuffer(audio, dtype=np.int16)
audio_as_np_float32 = audio_as_np_int16.astype(np.float32)
# Normalisation
max_int16 = 2**15
audio_normalised = audio_as_np_float32 / max_int16
return audio_normalised
#function that seprates the channels from a .WAV file
def save_wav_channel(fn, wav, channel):
#fn stands for file name on which the seperated channel needs to be save, wav sgtays the same and channel is nth channel it has seperated
# Read data
nch = wav.getnchannels()
depth = wav.getsampwidth()
wav.setpos(0)
sdata = wav.readframes(wav.getnframes())
# Extract channel data (24-bit data not supported)
typ = { 1: np.uint8, 2: np.uint16, 4: np.uint32 }.get(depth)
if not typ:
raise ValueError("sample width {} not supported".format(depth))
if channel >= nch:
raise ValueError("cannot extract channel {} out of {}".format(channel+1, nch))
print ("Extracting channel {} out of {} channels, {}-bit depth".format(channel+1, nch, depth*8))
data = np.fromstring(sdata, dtype=typ)
ch_data = data[channel::nch]
# Save channel to a separate file
outwav = wave.open(fn, 'w')
outwav.setparams(wav.getparams())
outwav.setnchannels(1)
outwav.writeframes(ch_data.tostring())
outwav.close()
wav = wave.open("/content/test3.wav")
save_wav_channel('T1.wav', wav, 0)
save_wav_channel('T2.wav', wav, 1)
import matplotlib.pyplot as plt
from scipy import signal
import numpy as np
def lag_finder(y1, y2, sr):
n = len(y1)
corr = signal.correlate(y2, y1, mode='same') / np.sqrt(signal.correlate(y1, y1, mode='same')[int(n/2)] * signal.correlate(y2, y2, mode='same')[int(n/2)])
delay_arr = np.linspace(-0.5*n/sr, 0.5*n/sr, n)
delay = delay_arr[np.argmax(corr)]
print('y2 is ' + str(delay) + ' behind y1')
plt.figure()
plt.plot(delay_arr, corr)
plt.title('Lag: ' + str(delay) + ' s')
plt.xlabel('Lag')
plt.ylabel('Correlation coeff')
plt.show()
print(np.argmax(corr))
return delay
a= MakeArray("/content/T1.wav")
b= MakeArray("/content/T2.wav")
d =lag_finder(a,b,48000)
print(d)
alpha = d*343/0.50
print(alpha)
angle = np.arcsin(alpha)
print()
degree = angle*180/(3.14)
print(str(degree) +"°")