You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python频谱图生成程序运行逐渐变慢的原因排查求助

音频转频谱图程序的性能与内存问题

我编写了一个Python程序,用于处理约9000个.wav音频文件:从CSV文件读取音频路径,将音频裁剪至约2.5秒时长,转换为频谱图后保存为PNG文件到对应文件夹。

程序初始运行速度很快,生成单张频谱图仅需约0.5秒,但随后速度持续下降——并非电脑热节流导致的稳定减速,而是每张频谱图的生成时间都比上一张更长。停止程序后立即重启,速度会恢复至约0.5秒每张。

最初我以为是未关闭音频文件导致资源堆积,在makeSpectrogram函数末尾添加了soundFile.close()语句,但问题并未改善。生成约500张频谱图后,单张耗时达到10.8秒,且仍在增加。

编辑:核心速度问题已解决,但出现了内存泄漏问题:生成约5500张频谱图后,电脑会提示内存不足,虽不影响程序运行但较为烦人。


程序代码

import csv
import time
import wave
import matplotlib.pyplot as plt
import numpy as np

# Function to make a spectrogram from a given wav file, and save it as a png to a given location

def makeSpectrogram(soundFilePath, fileSavePath, counter, station, species):
    soundFile = wave.open(soundFilePath, "r")

    # Get frame rate and number of frames
    frameRate = soundFile.getframerate()
    numFrames = soundFile.getnframes()
    
    # Extract the raw audio data
    rawAudio = soundFile.readframes(numFrames)
    
    # Convert the raw audio data to a NumPy array
    audio = np.frombuffer(rawAudio, dtype=np.int16)
    
    # Trim the audio
    reductionFactor = int((len(audio) - 500000) / 2)
    audio = audio[reductionFactor:-reductionFactor]
    
    # Create the spectrogram
    spectrogram = plt.specgram(audio, Fs=frameRate, NFFT=4096, noverlap=2048, cmap="Greys", )
    
    # Limit the y-axis to certain frequencies
    plt.ylim([15000, 90000])
    
    # Save the spectrogram as an image
    plt.savefig(f"{fileSavePath}spectrogram_station{station}_{species}_{counter}.png", dpi=250)
    
    # Close the file
    soundFile.close()

# Open CSV

csvFile = open("/Users/myname/Desktop/spreadsheet.csv", "r")
csv = csv.reader(csvFile)

# List from CSV

csvList = list(csv)

# Start timer

start = time.time()

# Loop through files in CSV, make spectrogram for each

for i in range(510, len(csvList)):
    row = csvList[i]
    wavPath = row[0]
    station = row[4]
    species = row[1]
    try:
        start2 = time.time()
        makeSpectrogram(wavPath, f"/Users/myname/Desktop/Spectrograms/Station {station}/uncropped/", i, station, species)
        print(f"Spectrogram complete: {wavPath}")
        end = time.time()
        print(f"Time Elapsed: {end - start} s")
        end2 = time.time()
        print(f"Render Time: {end2 - start2}")
        print(f"Estimated Time Remaining: {((end2 - start2) * (len(csvList) - i)) / 3600} hrs")
        print(f"Spectrograms Completed: {i}\n")
    except:
        print(f"File not found: {wavPath}")
        end = time.time()
        print(f"Time Elapsed: {end - start} s")
        print(f"Spectrograms Completed: {i}\n")

csvFile.close()

内容的提问来源于stack exchange,提问作者ray_drost

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 10:36:08