make a python script with a ui that can take two audio files and compare to waveforms to…
- User
make a python script with a ui that can take two audio files and compare to waveforms to see if they are the "same" by meeting a threshold
- Assistant
Certainly! Below is a Python script that creates a simple graphical user interface (GUI) using Tkinter. The GUI allows you to select two audio files (in WAV format) and compares their waveforms to determine if they are the same within a specified threshold.
import tkinter as tk from tkinter import filedialog, messagebox import numpy as np from scipy.io import wavfile # Function to load and process audio files def load_audio(file_path): try: sample_rate, data = wavfile.read(file_path) # Normalize data data = data / np.max(np.abs(data), axis=0) return sample_rate, data except Exception as e: messagebox.showerror("Error", f"Failed to load audio file:\n{e}") return None, None # Function to compare two audio files def compare_audio(): threshold = threshold_var.get() if not file1_path.get() or not file2_path.get(): messagebox.showwarning("Warning", "Please select two audio files.") return sr1, data1 = load_audio(file1_path.get()) sr2, data2 = load_audio(file2_path.get()) if data1 is None or data2 is None: return # Check if sample rates are the same if sr1 != sr2: messagebox.showwarning("Warning", "Sample rates of the audio files do not match.") return # Make sure both files have the same length min_length = min(len(data1), len(data2)) data1 = data1[:min_length] data2 = data2[:min_length] # Calculate the difference difference = np.abs(data1 - data2) mean_difference = np.mean(difference) # Compare mean difference with threshold if mean_difference <= threshold: result = "The audio files are the same within the threshold." else: result = "The audio files are different." # Display the result messagebox.showinfo("Result", result) # Function to browse and select file def browse_file(entry): file_path = filedialog.askopenfilename( filetypes=[("WAV Files", "*.wav"), ("All Files", "*.*")] ) if file_path: entry.set(file_path) # Create the main window root = tk.Tk() root.title("Audio File Comparator") # Variables to hold file paths and threshold file1_path = tk.StringVar() file2_path = tk.StringVar() threshold_var = tk.DoubleVar(value=0.01) # Create and place widgets tk.Label(root, text="Audio File 1:").grid(row=0, column=0, padx=10, pady=5, sticky="e") tk.Entry(root, textvariable=file1_path, width=50).grid(row=0, column=1, padx=10, pady=5) tk.Button(root, text="Browse...", command=lambda: browse_file(file1_path)).grid( row=0, column=2, padx=10, pady=5 ) tk.Label(root, text="Audio File 2:").grid(row=1, column=0, padx=10, pady=5, sticky="e") tk.Entry(root, textvariable=file2_path, width=50).grid(row=1, column=1, padx=10, pady=5) tk.Button(root, text="Browse...", command=lambda: browse_file(file2_path)).grid( row=1, column=2, padx=10, pady=5 ) tk.Label(root, text="Threshold:").grid(row=2, column=0, padx=10, pady=5, sticky="e") tk.Entry(root, textvariable=threshold_var).grid(row=2, column=1, padx=10, pady=5, sticky="w") tk.Button(root, text="Compare", command=compare_audio).grid( row=3, column=1, padx=10, pady=20 ) # Run the application root.mainloop()How the Script Works
-
Libraries Used:
tkinter: For building the GUI.numpy: For numerical operations on the audio data.scipy.io.wavfile: For reading WAV audio files.
-
GUI Components:
- File Selection: Two entry fields with "Browse..." buttons to select the audio files.
- Threshold Input: An entry field to input the threshold value for comparison.
- Compare Button: When clicked, it triggers the comparison of the two audio files.
-
Loading Audio Files:
- The
load_audiofunction reads the audio file and normalizes the waveform data to ensure consistent comparison.
- The
-
Comparing Audio Files:
- Checks if both audio files have the same sample rate.
- Trims the longer audio file to match the length of the shorter one.
- Calculates the absolute difference between the two waveforms.
- Computes the mean of the differences.
- Compares the mean difference to the user-defined threshold.
-
Displaying Results:
- The result is shown in a message box indicating whether the audio files are considered the same within the specified threshold.
Notes
-
Threshold Value: The default threshold is set to
0.01, but you can adjust it based on how strict you want the comparison to be. A smaller threshold means that the waveforms need to be more similar to be considered the same. -
Audio Formats: This script currently supports WAV files. To support other audio formats like MP3 or AAC, you can use the
pyduborlibrosalibrary.
Extending to Other Audio Formats
If you need to compare audio files in formats other than WAV, you can modify the
load_audiofunction as follows:from pydub import AudioSegment def load_audio(file_path): try: audio = AudioSegment.from_file(file_path) data = np.array(audio.get_array_of_samples()) # Ensure stereo audio is handled correctly if audio.channels > 1: data = data.reshape((-1, audio.channels)) # Normalize data data = data / np.max(np.abs(data), axis=0) sample_rate = audio.frame_rate return sample_rate, data except Exception as e: messagebox.showerror("Error", f"Failed to load audio file:\n{e}") return None, NoneNote: You'll need to install
pyduband haveffmpegoravlibinstalled on your system forpydubto handle various audio formats.pip install pydubDependencies
Make sure you have the necessary libraries installed. You can install them using
pip:pip install numpy scipyFor the extended version supporting more formats:
pip install pydubRunning the Script
-
Save the script to a file, for example,
audio_comparator.py. -
Run the script using Python 3:
python audio_comparator.py -
Use the GUI to select the two audio files and set your desired threshold.
-
Click the "Compare" button to see the result.
Important Considerations
- Sample Rates: The script assumes that both audio files should have the same sample rate for a valid comparison.
- Audio Length: If the audio files are of different lengths, the comparison is done up to the length of the shorter file.
- Stereo vs Mono: The script normalizes and compares multi-channel audio appropriately.
Feel free to adjust the script to suit your specific needs, such as refining the comparison method or enhancing the GUI.
-