0% found this document useful (0 votes)
4 views

application_code_exp2 (2)

The document outlines a Python script for audio password authentication using libraries such as pydub and librosa. It includes functions for converting audio formats, filtering noise, pitch and phase shifting, and computing correlation to authenticate audio passwords. The script processes stored and test audio files, generating variations and evaluating their correlation to determine authentication success.

Uploaded by

padwait205
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

application_code_exp2 (2)

The document outlines a Python script for audio password authentication using libraries such as pydub and librosa. It includes functions for converting audio formats, filtering noise, pitch and phase shifting, and computing correlation to authenticate audio passwords. The script processes stored and test audio files, generating variations and evaluating their correlation to determine authentication success.

Uploaded by

padwait205
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

# -*- coding: utf-8 -*-

"""audio_password_authentication.ipynb

Automatically generated by Colab.

Original file is located at

https://colab.research.google.com/drive/1sSwHvXkENx32Rh7g1I6FgbqDIUlUVwY
x
"""

!pip install pydub

import numpy as np
import scipy.io.wavfile as wav
import scipy.signal as signal
import matplotlib.pyplot as plt
from pydub import AudioSegment
import librosa
import librosa.effects

def convert_to_wav(input_file, output_file):


"""Converts an audio file (e.g., .m4a) to .wav format."""
audio = AudioSegment.from_file(input_file)
audio.export(output_file, format="wav")

def load_audio(filename):
sample_rate, data = wav.read(filename)
if data.ndim > 1:
data = data.mean(axis=1)
data = data.astype(np.float32)
data = librosa.util.normalize(data) # Normalize amplitude
return sample_rate, data

def filter_noise(data, cutoff=1000, fs=44100, order=6):


nyquist = 0.5 * fs
normal_cutoff = cutoff / nyquist
b, a = signal.butter(order, normal_cutoff, btype='low',
analog=False)
return signal.filtfilt(b, a, data)

def compute_correlation(signal1, signal2):


corr_matrix = np.corrcoef(signal1, signal2)
return corr_matrix[0, 1]
def plot_signal(signal_data, sample_rate, title):
time = np.arange(len(signal_data)) / sample_rate
plt.figure(figsize=(12, 6))
plt.plot(time, signal_data)
plt.title(title)
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.grid(True)
plt.show()

def pitch_shift(audio, sample_rate, semitones):


return librosa.effects.pitch_shift(audio, sr=sample_rate,
n_steps=semitones)

def phase_shift(audio, shift_amount):


return np.roll(audio, shift_amount)

def main():
stored_audio_file = '/content/password.m4a'
stored_wav_file = '/content/password.wav'
convert_to_wav(stored_audio_file, stored_wav_file)

test_audio_files = [
'/content/test-1.m4a',
'/content/test-2.m4a',
'/content/test-3.m4a',
'/content/test-4.m4a'
]

test_wav_files = [file.replace('.m4a', '.wav') for file in


test_audio_files]

for input_file, output_file in zip(test_audio_files,


test_wav_files):
convert_to_wav(input_file, output_file)

print("Loading and filtering stored audio password...")


stored_sample_rate, stored_password = load_audio(stored_wav_file)
stored_password_filtered = filter_noise(stored_password,
fs=stored_sample_rate)

# Generate additional test samples with variations


generated_files = []
variations = [
('test-5.wav', pitch_shift(stored_password_filtered,
stored_sample_rate, 2)),
('test-6.wav', pitch_shift(stored_password_filtered,
stored_sample_rate, -2)),
('test-7.wav', phase_shift(stored_password_filtered, 1000)),
('test-8.wav', phase_shift(stored_password_filtered, -1000))
]

for filename, modified_audio in variations:


wav.write(f'/content/{filename}', stored_sample_rate,
modified_audio)
generated_files.append(f'/content/{filename}')

all_test_files = test_wav_files + generated_files

threshold = 0.02

for test_wav_file in all_test_files:


print(f"Processing {test_wav_file}...")
test_sample_rate, test_password = load_audio(test_wav_file)
test_password_filtered = filter_noise(test_password,
fs=test_sample_rate)

min_length = min(len(stored_password_filtered),
len(test_password_filtered))
stored_password_filtered = stored_password_filtered[:min_length]
test_password_filtered = test_password_filtered[:min_length]

plot_signal(stored_password_filtered, stored_sample_rate,
'Stored Audio Password')
plot_signal(test_password_filtered, test_sample_rate, f'Test
Audio Password: {test_wav_file}')

correlation = compute_correlation(stored_password_filtered,
test_password_filtered)
print(f"Correlation with {test_wav_file}: {correlation:.2f}")

if correlation > threshold:


print(f"{test_wav_file}: Authentication successful!")
else:
print(f"{test_wav_file}: Authentication failed!")

if __name__ == "__main__":
main()

You might also like