Certainly! Below is a comprehensive guide and code example that demonstrates how to visualize both the audio waveform and its corresponding MFCC (Mel Frequency Cepstral Coefficients) features using Plotly in Python. This guide assumes you have already loaded the audio and computed the MFCCs as per your provided code.
Overview
-
Plotting the Audio Waveform:
- Visualize the amplitude of the audio signal over time.
-
Plotting the MFCC Features:
- Visualize the MFCCs as a heatmap to observe the frequency characteristics over time.
-
Combining Both Plots:
- Use Plotly's
make_subplots to display both visualizations side by side or stacked vertically.
Prerequisites
Ensure you have the necessary libraries installed. If not, you can install them using pip:
pip install plotly torch
Complete Code Example
import os
import torch
import numpy as np
import plotly.graph_objs as go
from plotly.subplots import make_subplots
# Assuming your audio_aud module is correctly set up and accessible
from audio_aud import (
load_audio,
MFCC,
)
def plot_audio_and_mfcc(audio_file_path, sample_rate=16000):
"""
Plots the audio waveform and its MFCC features using Plotly.
Parameters:
- audio_file_path (str): Path to the audio file.
- sample_rate (int): Sampling rate of the audio file.
"""
# Load audio
audio_array = load_audio(file=audio_file_path)
print(f"Audio shape: {audio_array.shape}") # e.g., (176000,)
# Compute MFCC
transform = MFCC(
sample_rate=sample_rate,
n_mfcc=13,
melkwargs={"n_fft": 400, "hop_length": 160, "n_mels": 40, "center": False},
)
mel_wav = transform(torch.from_numpy(audio_array))
mel_wav = mel_wav.numpy() # Convert to numpy for plotting
print(f"MFCC shape: {mel_wav.shape}") # e.g., (13, 1098)
# Time axis for waveform
duration = len(audio_array) / sample_rate
time_waveform = np.linspace(0, duration, num=len(audio_array))
# Time axis for MFCC
hop_length = 160
time_mfcc = np.linspace(0, duration, num=mel_wav.shape[1])
# Create subplots: 2 rows, 1 column
fig = make_subplots(
rows=2, cols=1,
shared_xaxes=True,
vertical_spacing=0.1,
subplot_titles=("Audio Waveform", "MFCC Features")
)
# Plot Audio Waveform
fig.add_trace(
go.Scatter(
x=time_waveform,
y=audio_array,
mode='lines',
name='Waveform',
line=dict(color='blue')
),
row=1, col=1
)
# Plot MFCC as Heatmap
fig.add_trace(
go.Heatmap(
z=mel_wav,
x=time_mfcc,
y=np.arange(1, mel_wav.shape[0] + 1),
colorscale='Viridis',
colorbar=dict(title='MFCC Coefficients'),
name='MFCC',
),
row=2, col=1
)
# Update layout
fig.update_layout(
height=800,
width=1000,
title_text="Audio Waveform and MFCC Visualization",
showlegend=False
)
# Update axes titles
fig.update_xaxes(title_text="Time (s)", row=1, col=1)
fig.update_yaxes(title_text="Amplitude", row=1, col=1)
fig.update_xaxes(title_text="Time (s)", row=2, col=1)
fig.update_yaxes(title_text="MFCC Coefficient", row=2, col=1)
# Show plot
fig.show()
# Example usage
if __name__ == "__main__":
audio_file_path = r"C:\Users\heman\Desktop\Coding\whisper\tests\jfk.flac"
# Check if the file exists
if not os.path.isfile(audio_file_path):
raise FileNotFoundError(f"The audio file was not found at the specified path: {audio_file_path}")
plot_audio_and_mfcc(audio_file_path)
Explanation of the Code
-
Function plot_audio_and_mfcc:
-
Parameters:
audio_file_path: The path to your audio file (e.g., .flac, .wav).
sample_rate: The sampling rate of the audio. Default is set to 16000 Hz.
-
Loading the Audio:
- Uses
load_audio from your audio_aud module to load the audio file into a NumPy array.
-
Computing MFCC:
- Initializes the
MFCC transformer with specified parameters.
- Transforms the audio array to compute MFCCs.
- Converts the resulting tensor to a NumPy array for plotting.
-
Creating Time Axes:
- For the waveform, the time axis is computed based on the number of samples and the sampling rate.
- For MFCCs, the time axis is computed based on the number of frames and the hop length.
-
Plotting with Plotly:
- Utilizes Plotly's
make_subplots to create a figure with two rows:
- First Row: Displays the audio waveform using
go.Scatter.
- Second Row: Displays the MFCCs as a heatmap using
go.Heatmap.
- Configures layout elements like titles, axis labels, and overall figure size.
- Displays the interactive plot using
fig.show().
-
Running the Script:
- The
if __name__ == "__main__": block ensures that the plotting function runs when the script is executed directly.
- It checks if the provided audio file path exists to prevent errors.
Customization Tips
Final Output
Running the provided script will generate an interactive Plotly figure with two subplots:
- Audio Waveform: Displays the amplitude of the audio signal over time.
- MFCC Features: Shows a heatmap where the x-axis represents time, the y-axis represents the MFCC coefficients, and the color intensity indicates the magnitude of each coefficient.
This visualization provides valuable insights into the temporal and frequency characteristics of the audio signal.
Feel free to integrate this code into your project and adjust parameters as needed for your specific use case!