Search code examples
pythonaudioscipysignal-processingwav

How to find timestamps of a specific sound in .wav file?


I have a .wav file that I recorded my own voice and speak for several minutes. Let's say I want to find the exact times that I said "Mike" in the audio. I looked into speech recognition and made some tests with Google Speech API, but the timestamps I got back were far from accurate.

As an alternative, I recorded a very short .wav file that I just said "Mike". I am trying to compare these two .wav files and find every timestamp that "Mike" was said in the longer .wav file. I came across SleuthEye's amazing answer

This code works perfectly well to find just one timestamp, but I couldn't figure out how to find out multiple start/end times:

import numpy as np
import sys
from scipy.io import wavfile
from scipy import signal

snippet = sys.argv[1]
source  = sys.argv[2]

# read the sample to look for
rate_snippet, snippet = wavfile.read(snippet);
snippet = np.array(snippet, dtype='float')

# read the source
rate, source = wavfile.read(source);
source = np.array(source, dtype='float')

# resample such that both signals are at the same sampling rate (if required)
if rate != rate_snippet:
  num = int(np.round(rate*len(snippet)/rate_snippet))
  snippet = signal.resample(snippet, num)

# compute the cross-correlation
z = signal.correlate(source, snippet);

peak = np.argmax(np.abs(z))
start = (peak-len(snippet)+1)/rate
end   = peak/rate

print("start {} end {}".format(start, end))

Solution

  • You were almost there. You can use find_peaks. For example

    import numpy as np
    from scipy.io import wavfile
    from scipy import signal
    import matplotlib.pyplot as plt
    
    snippet = 'snippet.wav'
    source  = 'source.wav'
    
    # read the sample to look for
    rate_snippet, snippet = wavfile.read(snippet);
    snippet = np.array(snippet[:,0], dtype='float')
    
    # read the source
    rate, source = wavfile.read(source);
    source = np.array(source[:,0], dtype='float')
    
    # resample such that both signals are at the same sampling rate (if required)
    if rate != rate_snippet:
        num = int(np.round(rate*len(snippet)/rate_snippet))
        snippet = signal.resample(snippet, num)
    

    My source and snippet

    x_snippet = np.arange(0, snippet.size) / rate_snippet
    
    plt.plot(x_snippet, snippet)
    plt.xlabel('seconds')
    plt.title('snippet')
    

    enter image description here

    x_source = np.arange(0, source.size) / rate
    
    plt.plot(x_source, source)
    plt.xlabel('seconds')
    plt.title('source')
    

    enter image description here

    Now we get the correlation

    # compute the cross-correlation
    z = signal.correlate(source, snippet, mode='same')
    

    I used mode='same' so that source and z have the same length

    source.size == z.size
    True
    

    Now, we can define a minimum peaks height, for example

    x_z = np.arange(0, z.size) / rate
    
    plt.plot(x_z, z)
    plt.axhline(2e20, color='r')
    plt.title('correlation')
    

    enter image description here

    and find peaks within a minimum distance (you may have to define your own height and distance depending on your samples)

    peaks = signal.find_peaks(
        z,
        height=2e20,
        distance=50000
    )
    
    peaks
    (array([ 117390,  225754,  334405,  449319,  512001,  593854,  750686,
             873026,  942586, 1064083]),
     {'peak_heights': array([8.73666562e+20, 9.32871542e+20, 7.23883305e+20, 9.30772354e+20,
             4.32924341e+20, 9.18323020e+20, 1.12473608e+21, 1.07752019e+21,
             1.12455724e+21, 1.05061734e+21])})
    

    We take the peaks idxs

    peaks_idxs = peaks[0]
    
    plt.plot(x_z, z)
    plt.plot(x_z[peaks_idxs], z[peaks_idxs], 'or')
    

    enter image description here

    Since they are "almost" in the middle of the snippet we can do

    fig, ax = plt.subplots(figsize=(12, 5))
    plt.plot(x_source, source)
    plt.xlabel('seconds')
    plt.title('source signal and correlatation')
    for i, peak_idx in enumerate(peaks_idxs):
        start = (peak_idx-snippet.size/2) / rate
        center = (peak_idx) / rate
        end   = (peak_idx+snippet.size/2) / rate
        plt.axvline(start,  color='g')
        plt.axvline(center, color='y')
        plt.axvline(end,    color='r')
        print(f"peak {i}: start {start:.2f} end {end:.2f}")
    
    peak 0: start 2.34 end 2.98
    peak 1: start 4.80 end 5.44
    peak 2: start 7.27 end 7.90
    peak 3: start 9.87 end 10.51
    peak 4: start 11.29 end 11.93
    peak 5: start 13.15 end 13.78
    peak 6: start 16.71 end 17.34
    peak 7: start 19.48 end 20.11
    peak 8: start 21.06 end 21.69
    peak 9: start 23.81 end 24.45
    

    enter image description here

    but there's maybe a better way to define more precisely start and end.