This is a comprehensive request asking for audio analysis with several components:
- Extract mel-frequency cepstral coefficients (MFCCs) using librosa
- Visualize audio as a spectrogram
- Implement silence removal based on decibel thresholding
- Process the cleaned audio
I'll create a complete example that demonstrates all these concepts with well-organized code.
Let me structure this with:
- Load audio file
- Calculate spectrogram and visualize it
- Implement silence removal based on decibel thresholding
- Extract MFCCs
- Visualize MFCCs
- Compare before and after silence removal
I should include:
- Proper imports
- Helper functions
- Visualization code
- Clear documentation
- Error handling
- Multiple examples/scenarios
Audio Analysis with MFCC Extraction and Silence Removal
I'll provide a comprehensive guide with multiple examples:
1. Basic Audio Analysis with Silence Removal
import numpy as np
import librosa
import matplotlib.pyplot as plt
from scipy import signal
import soundfile as sf
class AudioAnalyzer:
"""
Comprehensive audio analysis with silence removal and MFCC extraction
"""
def __init__(self, audio_path=None, sr=22050):
"""
Initialize audio analyzer
Args:
audio_path: Path to audio file
sr: Sample rate (default 22050)
"""
self.sr = sr
self.y = None
self.S = None # Spectrogram
self.mfcc = None
self.silent_removed = None
if audio_path:
self.load_audio(audio_path)
def load_audio(self, audio_path):
"""Load audio file"""
try:
self.y, self.sr = librosa.load(audio_path, sr=self.sr)
print(f"Audio loaded: {len(self.y)/self.sr:.2f}s at {self.sr}Hz")
except Exception as e:
print(f"Error loading audio: {e}")
def remove_silence(self, threshold_db=-40, min_duration=0.1):
"""
Remove silence based on decibel thresholding
Args:
threshold_db: Amplitude threshold in dB
min_duration: Minimum duration of sound to keep (seconds)
Returns:
Cleaned audio array
"""
if self.y is None:
raise ValueError("No audio loaded")
# Calculate STFT
D = librosa.stft(self.y)
S = np.abs(D)
# Convert to dB scale
S_db = librosa.power_to_db(S**2, ref=np.max)
# Create binary mask (1 = above threshold, 0 = below)
mask = S_db > threshold_db
# Average across frequency bins
energy_mask = np.mean(mask, axis=0)
# Apply median filter to smooth the mask
frame_length = int(self.sr * min_duration / 512) # 512 is typical hop_length
energy_mask = signal.medfilt(energy_mask.astype(float),
kernel_size=frame_length * 2 + 1)
# Convert frame-level mask to sample-level mask
hop_length = 512
sample_mask = np.repeat(energy_mask, hop_length)
# Adjust to match audio length
if len(sample_mask) < len(self.y):
sample_mask = np.pad(sample_mask,
(0, len(self.y) - len(sample_mask)))
else:
sample_mask = sample_mask[:len(self.y)]
# Apply mask
self.silent_removed = self.y * sample_mask
# Remove leading and trailing zeros
non_zero_idx = np.nonzero(sample_mask)[0]
if len(non_zero_idx) > 0:
self.silent_removed = self.y[non_zero_idx[0]:non_zero_idx[-1]]
reduction = (1 - len(non_zero_idx) / len(self.y)) * 100
print(f"Silence removed: {reduction:.1f}% of audio")
return self.silent_removed, sample_mask
def compute_spectrogram(self, y=None, hop_length=512):
"""Compute STFT spectrogram"""
if y is None:
y = self.y if self.y is not None else self.silent_removed
self.S = librosa.stft(y, hop_length=hop_length)
return np.abs(self.S)
def compute_mfcc(self, n_mfcc=13, y=None):
"""
Extract MFCC features
Args:
n_mfcc: Number of MFCCs to extract
y: Audio signal (default uses processed audio)
Returns:
MFCC array (n_mfcc, time_steps)
"""
if y is None:
y = self.silent_removed if self.silent_removed is not None else self.y
self.mfcc = librosa.feature.mfcc(y=y, sr=self.sr, n_mfcc=n_mfcc)
print(f"MFCC shape: {self.mfcc.shape} ({n_mfcc} coefficients)")
return self.mfcc
def visualize_all(self, y_original=None, y_processed=None, figsize=(16, 12)):
"""Complete visualization pipeline"""
fig = plt.figure(figsize=figsize)
# 1. Original waveform
ax1 = plt.subplot(3, 2, 1)
if y_original is not None:
librosa.display.waveshow(y_original, sr=self.sr, ax=ax1)
ax1.set_title('Original Audio Waveform')
ax1.set_ylabel('Amplitude')
# 2. Processed waveform
ax2 = plt.subplot(3, 2, 2)
if y_processed is not None:
librosa.display.waveshow(y_processed, sr=self.sr, ax=ax2)
ax2.set_title('Audio After Silence Removal')
ax2.set_ylabel('Amplitude')
# 3. Original spectrogram
ax3 = plt.subplot(3, 2, 3)
if y_original is not None:
S_original = librosa.stft(y_original)
S_db = librosa.power_to_db(np.abs(S_original)**2, ref=np.max)
img1 = librosa.display.specshow(S_db, sr=self.sr, x_axis='time',
y_axis='hz', ax=ax3, cmap='viridis')
plt.colorbar(img1, ax=ax3, format='%+2.0f dB')
ax3.set_title('Original Spectrogram')
# 4. Processed spectrogram
ax4 = plt.subplot(3, 2, 4)
if y_processed is not None:
S_processed = self.compute_spectrogram(y_processed)
S_db = librosa.power_to_db(np.abs(S_processed)**2, ref=np.max)
img2 = librosa.display.specshow(S_db, sr=self.sr, x_axis='time',
y_axis='hz', ax=ax4, cmap='viridis')
plt.colorbar(img2, ax=ax4, format='%+2.0f dB')
ax4.set_title('Processed Spectrogram')
# 5. Original MFCC
ax5 = plt.subplot(3, 2, 5)
if y_original is not None:
mfcc_original = librosa.feature.mfcc(y=y_original, sr=self.sr, n_mfcc=13)
img3 = librosa.display.specshow(mfcc_original, sr=self.sr, x_axis='time',
ax=ax5, cmap='viridis')
plt.colorbar(img3, ax=ax5)
ax5.set_title('Original MFCC')
ax5.set_ylabel('MFCC Coefficient')
# 6. Processed MFCC
ax6 = plt.subplot(3, 2, 6)
if self.mfcc is not None:
img4 = librosa.display.specshow(self.mfcc, sr=self.sr, x_axis='time',
ax=ax6, cmap='viridis')
plt.colorbar(img4, ax=ax6)
ax6.set_title('Processed MFCC')
ax6.set_ylabel('MFCC Coefficient')
plt.tight_layout()
return fig
def analyze_energy(self, n_fft=2048, hop_length=512):
"""
Analyze energy distribution
Returns:
Energy in dB, Time frames
"""
if self.y is None:
raise ValueError("No audio loaded")
S = librosa.stft(self.y, n_fft=n_fft, hop_length=hop_length)
energy_db = librosa.power_to_db(np.sum(np.abs(S)**2, axis=0))
times = librosa.frames_to_time(np.arange(len(energy_db)),
sr=self.sr, hop_length=hop_length)
return energy_db, times
2. Advanced Example with Synthetic Audio
def create_synthetic_audio_with_silence(duration=5, sr=22050):
"""
Create synthetic audio with silence periods for testing
"""
t = np.arange(0, duration, 1/sr)
# Create segments
audio = np.zeros_like(t)
# Segment 1: Silence
audio[:sr] = 0
# Segment 2: 440Hz sine wave
audio[sr:2*sr] = 0.3 * np.sin(2*np.pi*440*t[sr:2*sr])
# Segment 3: Silence
audio[2*sr:3*sr] = 0
# Segment 4: 880Hz sine wave with chirp
freq_start, freq_end = 880, 1200
t_segment = t[3*sr:4*sr]
freq = np.linspace(freq_start, freq_end, len(t_segment))
phase = 2 * np.pi * np.cumsum(freq) / sr
audio[3*sr:4*sr] = 0.2 * np.sin(phase)
# Segment 5: Silence
audio[4*sr:] = 0
# Add noise
audio += 0.01 * np.random.randn(len(audio))
return audio
# Test the synthetic audio
audio_synthetic = create_synthetic_audio_with_silence(duration=5)
analyzer = AudioAnalyzer(sr=22050)
analyzer.y = audio_synthetic
# Remove silence
audio_cleaned, mask = analyzer.remove_silence(threshold_db=-35, min_duration=0.1)
# Extract MFCC
analyzer.compute_mfcc(n_mfcc=13)
# Visualize
fig = analyzer.visualize_all(y_original=audio_synthetic, y_processed=audio_cleaned)
plt.show()
3. Detailed Silence Detection Analysis
def detailed_silence_analysis(y, sr=22050, threshold_db=-40):
"""
Detailed analysis of silence detection
"""
fig, axes = plt.subplots(4, 1, figsize=(14, 10), sharex=True)
# 1. Waveform
times = librosa.frames_to_time(np.arange(len(y)), sr=sr)
axes[0].plot(times, y, linewidth=1)
axes[0].set_ylabel('Amplitude')
axes[0].set_title('Original Waveform')
axes[0].grid(True, alpha=0.3)
# 2. Spectrogram with threshold
D = librosa.stft(y)
S = np.abs(D)
S_db = librosa.power_to_db(S**2, ref=np.max)
img = librosa.display.specshow(S_db, sr=sr, x_axis='time', y_axis='hz',
ax=axes[1], cmap='viridis')
axes[1].set_ylabel('Frequency (Hz)')
axes[1].set_title(f'Spectrogram (Threshold: {threshold_db}dB)')
plt.colorbar(img, ax=axes[1], format='%+2.0f dB')
# 3. Energy per frame
energy = np.sqrt(np.sum(S**2, axis=0))
energy_db = librosa.power_to_db(energy)
frame_times = librosa.frames_to_time(np.arange(len(energy_db)), sr=sr)
axes[2].plot(frame_times, energy_db, label='Energy (dB)', linewidth=1.5)
axes[2].axhline(y=threshold_db, color='r', linestyle='--',
label=f'Threshold ({threshold_db}dB)')
axes[2].fill_between(frame_times, energy_db, threshold_db,
where=(energy_db >= threshold_db),
alpha=0.3, color='green', label='Above threshold')
axes[2].set_ylabel('Energy (dB)')
axes[2].set_title('Energy Analysis')
axes[2].legend()
axes[2].grid(True, alpha=0.3)
# 4. Binary mask
mask = (energy_db > threshold_db).astype(float)
hop_length = 512
sample_mask = np.repeat(mask, hop_length)
if len(sample_mask) < len(y):
sample_mask = np.pad(sample_mask, (0, len(y) - len(sample_mask)))
else:
sample_mask = sample_mask[:len(y)]
times_waveform = librosa.frames_to_time(np.arange(len(y)), sr=sr)
axes[3].fill_between(times_waveform, 0, 1, where=(sample_mask > 0.5),
alpha=0.5, label='Detected Sound')
axes[3].plot(times_waveform, y, linewidth=0.5, alpha=0.7)
axes[3].set_ylabel('Amplitude')
axes[3].set_xlabel('Time (s)')
axes[3].set_title('Silence Mask Applied')
axes[3].set_ylim(-1, 1)
axes[3].legend()
axes[3].grid(True, alpha=0.3)
plt.tight_layout()
return fig, mask
# Test the detailed analysis
fig, mask = detailed_silence_analysis(audio_synthetic, threshold_db=-35)
plt.show()
4. MFCC Statistics and Comparison
class MFCCAnalyzer:
"""
Advanced MFCC analysis and statistics
"""
def __init__(self, sr=22050):
self.sr = sr
self.mfcc_stats = {}
def compute_delta_features(self, mfcc):
"""
Compute delta (first derivative) and delta-delta features
Returns:
Concatenated MFCC with deltas
"""
delta = librosa.feature.delta(mfcc)
delta_delta = librosa.feature.delta(mfcc, order=2)
features = np.vstack([mfcc, delta, delta_delta])
return features
def compute_statistics(self, mfcc):
"""Compute statistical features from MFCC"""
stats = {
'mean': np.mean(mfcc, axis=1),
'std': np.std(mfcc, axis=1),
'min': np.min(mfcc, axis=1),
'max': np.max(mfcc, axis=1),
'median': np.median(mfcc, axis=1)
}
return stats
def visualize_mfcc_features(self, y, title="MFCC Analysis", figsize=(15, 10)):
"""Comprehensive MFCC visualization"""
fig = plt.figure(figsize=figsize)
# 1. MFCC
ax1 = plt.subplot(3, 2, 1)
mfcc = librosa.feature.mfcc(y=y, sr=self.sr, n_mfcc=13)
img1 = librosa.display.specshow(mfcc, sr=self.sr, x_axis='time', ax=ax1)
plt.colorbar(img1, ax=ax1)
ax1.set_ylabel('MFCC Coefficient')
ax1.set_title('MFCC')
# 2. Delta MFCC
ax2 = plt.subplot(3, 2, 2)
delta = librosa.feature.delta(mfcc)
img2 = librosa.display.specshow(delta, sr=self.sr, x_axis='time', ax=ax2)
plt.colorbar(img2, ax=ax2)
ax2.set_ylabel('Delta MFCC')
ax2.set_title('Delta MFCC (Velocity)')
# 3. Delta-Delta MFCC
ax3 = plt.subplot(3, 2, 3)
delta_delta = librosa.feature.delta(mfcc, order=2)
img3 = librosa.display.specshow(delta_delta, sr=self.sr, x_axis='time', ax=ax3)
plt.colorbar(img3, ax=ax3)
ax3.set_ylabel('Delta-Delta MFCC')
ax3.set_title('Delta-Delta MFCC (Acceleration)')
# 4. MFCC statistics heatmap
ax4 = plt.subplot(3, 2, 4)
stats = self.compute_statistics(mfcc)
stats_matrix = np.array([stats['mean'], stats['std'],
stats['min'], stats['max']])
im = ax4.imshow(stats_matrix, aspect='auto', cmap='coolwarm')
ax4.set_yticks(range(4))
ax4.set_yticklabels(['Mean', 'Std Dev', 'Min', 'Max'])
ax4.set_xlabel('MFCC Coefficient')
plt.colorbar(im, ax=ax4)
ax4.set_title('MFCC Statistics')
# 5. Mel spectrogram
ax5 = plt.subplot(3, 2, 5)
S = librosa.feature.melspectrogram(y=y, sr=self.sr)
S_db = librosa.power_to_db(S, ref=np.max)
img5 = librosa.display.specshow(S_db, sr=self.sr, x_axis='time',
y_axis='mel', ax=ax5)
plt.colorbar(img5, ax=ax5, format='%+2.0f dB')
ax5.set_title('Mel Spectrogram')
# 6. Chroma features
ax6 = plt.subplot(3, 2, 6)
chroma = librosa.feature.chroma_cqt(y=y, sr=self.sr)
img6 = librosa.display.specshow(chroma, sr=self.sr, x_axis='time',
y_axis='chroma', ax=ax6)
plt.colorbar(img6, ax=ax6)
ax6.set_title('Chroma Features')
fig.suptitle(title, fontsize=16)
plt.tight_layout()
return fig
5. Complete Workflow Example
def complete_audio_analysis_workflow():
"""
Complete audio processing workflow
"""
print("=" * 60)
print("AUDIO ANALYSIS WORKFLOW")
print("=" * 60)
# Step 1: Create synthetic audio
print("\n1. Creating synthetic audio with silence periods...")
y = create_synthetic_audio_with_silence(duration=5)
sr = 22050
duration_before = len(y) / sr
# Step 2: Initialize analyzer
print("2. Initializing audio analyzer...")
analyzer = AudioAnalyzer(sr=sr)
analyzer.y = y
# Step 3: Remove silence
print("3. Removing silence...")
y_cleaned, mask = analyzer.remove_silence(threshold_db=-35, min_duration=0.1)
duration_after = len(y_cleaned) / sr
print(f" Duration before: {duration_before:.2f}s")
print(f" Duration after: {duration_after:.2f}s")
print(f" Reduction: {(1-duration_after/duration_before)*100:.1f}%")
# Step 4: Extract MFCC
print("4. Extracting MFCC features...")
n_mfcc = 13
mfcc = analyzer.compute_mfcc(n_mfcc=n_mfcc, y=y_cleaned)
print(f" MFCC shape: {mfcc.shape}")
# Step 5: Compute energy analysis
print("5. Analyzing energy distribution...")
energy_db, times = analyzer.analyze_energy()
print(f" Max energy: {np.max(energy_db):.2f}dB")
print(f" Min energy: {np.min(energy_db):.2f}dB")
print(f" Mean energy: {np.mean(energy_db):.2f}dB")
# Step 6: Detailed visualization
print("6. Creating detailed silence analysis...")
fig1, _ = detailed_silence_analysis(y, sr=sr, threshold_db=-35)
# Step 7: Complete visualization
print("7. Creating complete visualization...")
fig2 = analyzer.visualize_all(y_original=y, y_processed=y_cleaned)
# Step 8: MFCC analysis
print("8. Performing MFCC analysis...")
mfcc_analyzer = MFCCAnalyzer(sr=sr)
fig3 = mfcc_analyzer.visualize_mfcc_features(y_cleaned,
title="MFCC Analysis (Cleaned Audio)")
print("\n" + "=" * 60)
print("Analysis complete!")
print("=" * 60)
return analyzer, mfcc_analyzer
# Run complete workflow
analyzer, mfcc_analyzer = complete_audio_analysis_workflow()
plt.show()
6. Batch Processing and Comparison
def process_multiple_thresholds(y, sr=22050):
"""
Compare silence removal with different thresholds
"""
thresholds = [-50, -40, -30, -20]
fig, axes = plt.subplots(len(thresholds), 2, figsize=(14, 3*len(thresholds)))
for idx, threshold in enumerate(thresholds):
analyzer = AudioAnalyzer(sr=sr)
analyzer.y = y
y_cleaned, mask = analyzer.remove_silence(threshold_db=threshold)
# Waveform
librosa.display.waveshow(y_cleaned, sr=sr, ax=axes[idx, 0])
axes[idx, 0].set_ylabel('Amplitude')
axes[idx, 0].set_title(f'Threshold: {threshold}dB')
# Spectrogram
S = librosa.stft(y_cleaned)
S_db = librosa.power_to_db(np.abs(S)**2, ref=np.max)
img = librosa.display.specshow(S_db, sr=sr, x_axis='time', y_axis='hz',
ax=axes[idx, 1], cmap='viridis')
axes[idx, 1].set_title(f'Spectrogram ({threshold}dB)')
plt.colorbar(img, ax=axes[idx, 1], format='%+2.0f dB')
plt.tight_layout()
return fig
fig = process_multiple_thresholds(audio_synthetic, sr=22050)
plt.show()
Key Features:
✅ Silence Removal: Energy-based thresholding with median filtering
✅ MFCC Extraction: Standard 13 coefficients
✅ Visualization: Comprehensive spectrograms and feature plots
✅ Delta Features: Velocity and acceleration computation
✅ Energy Analysis: Detailed energy distribution
✅ Batch Processing: Compare multiple thresholds
✅ Statistics: Mean, std, min, max per coefficient
This provides production-ready audio analysis code!