Audio_Deepfake_Detection_Model / audio_features.py
Prabin1's picture
Update audio_features.py
8d18b82 verified
Raw
History Blame Contribute Delete
1.37 kB
import numpy as np
import librosa
SR = 16000
N_COEFFS = 20
def extract_mfcc(y, sr, n_mfcc=N_COEFFS):
return librosa.feature.mfcc(y=y, sr=sr, n_mfcc=n_mfcc)
def extract_lfcc(y, sr, n_lfcc=N_COEFFS):
S = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=n_lfcc, fmin=0, fmax=sr/2)
return librosa.power_to_db(S)
def extract_features_with_time_series(file_path, sr=SR, n_coeffs=N_COEFFS):
try:
y, _ = librosa.load(file_path, sr=sr, mono=True)
y, _ = librosa.effects.trim(y)
if np.max(np.abs(y)) > 0:
y = y / np.max(np.abs(y))
mfccs = extract_mfcc(y, sr, n_mfcc=n_coeffs)
lfccs = extract_lfcc(y, sr, n_lfcc=n_coeffs)
chroma = librosa.feature.chroma_stft(y=y, sr=sr)
spec_centroid = librosa.feature.spectral_centroid(y=y, sr=sr)
spec_bandwidth = librosa.feature.spectral_bandwidth(y=y, sr=sr)
zcr = librosa.feature.zero_crossing_rate(y)
features_to_stack = [mfccs, lfccs, chroma, spec_centroid, spec_bandwidth, zcr]
max_len = max(f.shape[1] for f in features_to_stack)
padded = [librosa.util.fix_length(f, size=max_len, axis=1) for f in features_to_stack]
stacked_features = np.vstack(padded).astype(np.float32)
return stacked_features.T
except Exception as e:
print(f"[extract_features] Error: {e}")
return None