import numpy as np from scipy.io.wavfile import read, write from scipy.signal import butter, filtfilt from argparse import ArgumentParser import os import subprocess import tempfile from time import strftime, localtime parser = ArgumentParser(prog='python3 audio_detect.py', description='Example script that uses ffmpeg and bandpass filter to locate audio signature') parser.add_argument('video', type=str, help='Video file to analyze') args = parser.parse_args() if not os.path.exists(args.video) : print(f'Video {args.video} does not exist') exit(1) print(f'Detecting audio signature in {args.video}') def rm (file) : if os.path.exists(file): os.remove(file) def bandpass_filter(data, lowcut, highcut, fs, order=5): """Apply a bandpass filter to the audio data.""" nyq = 0.5 * fs low = lowcut / nyq high = highcut / nyq b, a = butter(order, [low, high], btype='band') y = filtfilt(b, a, data) return y def apply_bandpass_to_wav(input_file, output_file, lowcut, highcut, order=5): """Read a WAV file, apply a bandpass filter, and write the result to a new WAV file.""" fs, data = read(input_file) print(f'Applying {lowcut} -> {highcut} bandpass on {input_file}') if data.ndim == 2: filtered_data = np.zeros_like(data) for channel in range(data.shape[1]): filtered_data[:, channel] = bandpass_filter(data[:, channel], lowcut, highcut, fs, order) else: filtered_data = bandpass_filter(data, lowcut, highcut, fs, order) write(output_file, fs, filtered_data.astype(np.int16)) def export_audio (video) : print(f'Exporting audio from {video}...') tmp_file, filename = tempfile.mkstemp(suffix='.wav') cmd = [ 'ffmpeg', '-hwaccel', 'auto', '-y', '-i', f'"{video}"', '-vn', '-acodec', 'pcm_s16le', f'"{filename}"' ] proc = subprocess.Popen(' '.join(cmd), stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, shell = True) for line in proc.stdout : #print(line.decode('ascii').strip()) a=1 return filename audio_file = export_audio(args.video) print(audio_file) apply_bandpass_to_wav(audio_file, 'extracted.wav', 290, 310) #rm(audio_file)