Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Check if two audio files have identical audio
#!/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()
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")
exit_status = 0
else:
print("Different")
exit_status = 1
#Delete temporary directory
shutil.rmtree(temp_dir)
sys.exit(exit_status)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment