Last active
February 5, 2022 22:19
-
-
Save jack126guy/9ce2b7d1d427b335eb6e2b68cedcf8e5 to your computer and use it in GitHub Desktop.
Check if two audio files have identical audio
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
"""Check if two audio files have identical audio. | |
The ffmpeg command-line utility must be installed. | |
Usage: python audiocmp.py [file 1] [file 2] | |
""" | |
import sys | |
import tempfile | |
import shutil | |
import os | |
import subprocess | |
import wave | |
"""How many frames should be compared at one time""" | |
FRAME_BLOCK_SIZE = 1024 | |
"""Convert an audio file and open it as a WAVE object. | |
Arguments: | |
file -- Name of original audio file | |
conv_file -- Name of converted file | |
Returns: wave.Wave_read object to the converted file | |
""" | |
def wave_convert_open(file, conv_file): | |
subprocess.call(["ffmpeg", "-i", file, conv_file]) | |
return wave.open(conv_file) | |
"""Compare the audio in two wave files. | |
Arguments: | |
wave_1 -- wave.Wave_read object for the first file | |
wave_2 -- wave.Wave_read object for the second file | |
Returns: True if the audio in the two files is the same, False otherwise | |
""" | |
def wave_compare(wave_1, wave_2): | |
#Compare paramters | |
if wave_1.getparams() != wave_2.getparams(): | |
return False | |
#Compare frames | |
while True: | |
frames_1 = wave_1.readframes(FRAME_BLOCK_SIZE) | |
frames_2 = wave_2.readframes(FRAME_BLOCK_SIZE) | |
if frames_1 == b"": | |
break | |
if frames_1 != frames_2: | |
return False | |
return True | |
#Check and extract command-line arguments | |
if len(sys.argv) < 3: | |
print(__doc__) | |
sys.exit(2) | |
filename_1, filename_2 = sys.argv[1:3] | |
#Create temporary directory | |
temp_dir = tempfile.mkdtemp() | |
try: | |
conv_filename_1 = os.path.join(temp_dir, "1.wav") | |
conv_filename_2 = os.path.join(temp_dir, "2.wav") | |
wave_1 = wave_convert_open(filename_1, conv_filename_1) | |
wave_2 = wave_convert_open(filename_2, conv_filename_2) | |
if wave_compare(wave_1, wave_2): | |
print("Same") | |
sys.exit(0) | |
else: | |
print("Different") | |
sys.exit(1) | |
except Exception as e: | |
print(repr(e)) | |
sys.exit(2) | |
finally: | |
#Delete temporary directory | |
shutil.rmtree(temp_dir) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment