毕业设计:多音频文件频谱图批量提取代码求助
Batch Spectrogram Extraction for Music Genre Classification
Hey there! Let's get your batch spectrogram extraction working smoothly for your thesis—you've got the core single-file logic down, we just need to tweak the loop to handle multiple files properly. Here's what's missing in your current code and how to fix it:
Key Issues in Your Current Code
- You're looping over an index range, but not actually loading each individual audio file (your
xandsrvariables are still tied to a single audio file outside the loop) - There's no logic to save the generated spectrograms (critical for batch processing—you don't want to just display them one by one!)
- No cleanup of matplotlib figures, which will eat up memory as you process more files
Fixed & Annotated Code
First, make sure you've imported all required libraries:
import os import librosa import librosa.display import matplotlib.pyplot as plt
Then, here's the updated batch processing code:
# First, make sure audio_path is a list of ALL your audio file paths # Example to get all .wav/mp3 files in a folder: # audio_path = librosa.util.find_files("path/to/your/audio_directory", ext=["wav", "mp3"]) # Loop through each audio file path directly (no need for range indexes) for file_path in audio_path: try: # Load the current audio file (sr=None preserves original sample rate) x, sr = librosa.load(file_path, sr=None) # Compute STFT and convert to dB scale (same as your single-file logic) X = librosa.stft(x) Xdb = librosa.amplitude_to_db(abs(X)) # Set up the figure plt.figure(figsize=(14, 5)) librosa.display.specshow(Xdb, sr=sr, x_axis='time', y_axis='hz') plt.colorbar(format='%+2.0f dB') plt.title(f"Spectrogram: {os.path.basename(file_path)}") # Save the spectrogram to a file (use original filename to stay organized) output_filename = f"{os.path.splitext(os.path.basename(file_path))[0]}_spectrogram.png" # Optional: Specify a dedicated output folder # output_path = os.path.join("path/to/save/spectrograms", output_filename) plt.savefig(output_filename, bbox_inches='tight') # Close the figure to free up memory (essential for large batches!) plt.close() print(f"Processed: {file_path}") except Exception as e: # Handle errors (like corrupted files) so the loop doesn't break print(f"Failed to process {file_path}: {str(e)}")
Quick Tips
- Path Organization: Use
os.path.jointo handle file paths seamlessly across Windows/macOS/Linux - Filter Formats: Use
librosa.util.find_fileswithext=["wav", "mp3"]to target specific audio types if your folder has mixed files - Logarithmic Axis: Uncomment the
y_axis='log'line inspecshowif you want a log-scale frequency axis—this is common for music analysis - Progress Tracking: For large datasets, add a progress bar with the
tqdmlibrary to keep tabs on processing speed
内容的提问来源于stack exchange,提问作者Atharva Athaley
相关产品推荐
相关产品推荐

