Python cross correlation

This code will help in finding the delay between two channels in audio file

xin, fs = sf.read('recording1.wav')
frame_len = int(fs*5*1e-3)
dim_x =xin.shape
M = dim_x[0] # No. of rows
N= dim_x[1] # No. of col
sample_lim = frame_len*100
tau = [0]
M_lim = 20000 # for testing as processing takes time
for i in range(1,N):
    c = np.correlate(xin[0:M_lim,0],xin[0:M_lim,i],"full")
    maxlags = M_lim-1
    c = c[M_lim -1 -maxlags: M_lim + maxlags]
    Rmax_pos = np.argmax(c)
    pos = Rmax_pos-M_lim+1
    tau.append(pos)
print(tau)

numpy.correlate(arr1,arr2,"full")

gave me same output as

xcorr(arr1,arr2)

gives in matlab


Implementation of MATLAB xcorr(x,y) and comparision of result with example.

import scipy.signal as signal
def xcorr(x,y):
    """
    Perform Cross-Correlation on x and y
    x    : 1st signal
    y    : 2nd signal

    returns
    lags : lags of correlation
    corr : coefficients of correlation
    """
    corr = signal.correlate(x, y, mode="full")
    lags = signal.correlation_lags(len(x), len(y), mode="full")
    return lags, corr

n = np.array([i for i in range(0,15)])
x = 0.84**n
y = np.roll(x,5);
lags,c = xcorr(x,y);
plt.figure()
plt.stem(lags,c)
plt.show()

output resembling matlab xcorr output