Python 为什么我的记忆在流失?

Python 为什么我的记忆在流失?,python,audio,memory,detection,recording,Python,Audio,Memory,Detection,Recording,这里有一个脚本,用来检测和记录我窃听了一段时间的声音。它工作得很好,只是每次成功检测后内存使用量都会增加。我修复了在长时间的沉默中出现的类似问题(if num\u listing>4096:…),但这一问题让我感到困惑 from sys import byteorder from array import array from struct import pack from datetime import datetime import pyaudio import wave import

这里有一个脚本,用来检测和记录我窃听了一段时间的声音。它工作得很好,只是每次成功检测后内存使用量都会增加。我修复了在长时间的沉默中出现的类似问题(
if num\u listing>4096:
…),但这一问题让我感到困惑


from sys import byteorder
from array import array
from struct import pack
from datetime import datetime

import pyaudio
import wave
import os
import time

THRESHOLD = 6348
MAX_SILENCE = 500
CHUNK_SIZE = 1024
FORMAT = pyaudio.paInt16
RATE = 44100
MAX_LENGTH = 1024

def is_silent(snd_data):
    "Returns 'True' if below the 'silent' threshold"
    return max(snd_data) < THRESHOLD

def normalize(snd_data):
    "Average the volume out"
    MAXIMUM = 16384
    times = float(MAXIMUM)/max(abs(i) for i in snd_data)

    r = array('h')
    for i in snd_data:
        r.append(int(i*times))
    return r

def trim(snd_data):
    "Trim the blank spots at the start and end"
    def _trim(snd_data):
        snd_started = False
        r = array('h')

        for i in snd_data:
            if not snd_started and abs(i) > THRESHOLD:
                snd_started = True
                r.append(i)

            elif snd_started:
                r.append(i)
        return r

    # Trim to the left
    snd_data = _trim(snd_data)

    # Trim to the right
    snd_data.reverse()
    snd_data = _trim(snd_data)
    snd_data.reverse()
    return snd_data

def add_silence(snd_data, seconds):
    "Add silence to the start and end of 'snd_data' of length 'seconds' (float)"
    silence = [0] * int(seconds * RATE)
    r = array('h', silence)
    r.extend(snd_data)
    r.extend(silence)
    return r

def record():
    """
    Record a word or words from the microphone and 
    return the data as an array of signed shorts.

    Normalizes the audio, trims silence from the 
    start and end, and pads with 0.5 seconds of 
    blank sound to make sure VLC et al can play 
    it without getting chopped off.
    """
    p = pyaudio.PyAudio()
    stream = p.open(format=FORMAT, channels=1, rate=RATE,
        input=True, output=True,
        frames_per_buffer=CHUNK_SIZE)

    num_silent = 0
    num_snd = 0
    num_listening = 0
    snd_started = False

    r = array('h')

    while num_snd < MAX_LENGTH:
        # little endian, signed short
        snd_data = array('h', stream.read(CHUNK_SIZE, exception_on_overflow = False))
        if byteorder == 'big':
            snd_data.byteswap()
        r.extend(snd_data)

        silent = is_silent(snd_data)

        if not silent and not snd_started:
            snd_started = True

        if snd_started:
            num_snd += 1
            if num_silent > MAX_SILENCE:
                break

        if silent:
            if snd_started:
                num_silent += 1
            if not snd_started:
                num_listening += 1
                if num_listening > 4096:
                    del r[:]
                    num_listening = 0

    sample_width = p.get_sample_size(FORMAT)
    stream.stop_stream()
    stream.close()
    p.terminate()

    del r[0:8000]

    r = normalize(r)
    r = trim(r)
    r = add_silence(r, 0.5)
    return sample_width, r

def record_to_file(path):
    "Records from the microphone and outputs the resulting data to 'path'"
    sample_width, data = record()
    data = pack('<' + ('h'*len(data)), *data)

    wf = wave.open(path, 'wb')
    wf.setnchannels(1)
    wf.setsampwidth(sample_width)
    wf.setframerate(RATE)
    wf.writeframes(data)
    wf.close()

if __name__ == '__main__':
    while True:
        print("Ready!")
        recorded = datetime.now()
        recorded = "testpi1_" + recorded.strftime("%Y-%m-%d--%H-%M-%S") + ".wav"
        record_to_file("/motion/" + recorded)
        os.system("./convert-audio.py " + recorded)

从sys导入字节顺序
从数组导入数组
从结构导入包
从日期时间导入日期时间
导入pyaudio
输入波
导入操作系统
导入时间
阈值=6348
最大静音=500
块大小=1024
格式=pyaudio.paInt16
费率=44100
最大长度=1024
def静音(snd数据):
“如果低于“静默”阈值,则返回“True”
返回最大值(snd_数据)<阈值
def正常化(snd_数据):
“求出卷的平均值”
最大值=16384
时间=浮动(最大)/最大值(snd_数据中i的绝对值(i))
r=数组('h')
对于snd_数据中的i:
r、 追加(整数(i*次))
返回r
def微调(snd_数据):
“在开始和结束时修剪空白点”
def_微调(snd_数据):
snd_start=False
r=数组('h')
对于snd_数据中的i:
如果未启动snd_且abs(i)>阈值:
snd_start=True
r、 附加(i)
elif snd_开始:
r、 附加(i)
返回r
#向左修剪
snd_数据=_修剪(snd_数据)
#向右修剪
snd_data.reverse()
snd_数据=_修剪(snd_数据)
snd_data.reverse()
返回snd_数据
def添加_静音(snd_数据,秒):
“为长度为“秒”(浮动)的“snd_数据”的开始和结束添加静音”
静默=[0]*int(秒*速率)
r=数组('h',静音)
r、 扩展(snd_数据)
r、 延长(沉默)
返回r
def记录():
"""
从麦克风录制一个或多个单词,然后
将数据作为带符号的短字符数组返回。
使音频正常化,从
开始和结束,并用0.5秒的
空白声音,确保VLC等可以播放
它没有被砍掉。
"""
p=pyaudio.pyaudio()
流=p.open(格式=格式,通道=1,速率=速率,
输入=真,输出=真,
每个缓冲区的帧数=块大小)
num_silent=0
num\u snd=0
num_侦听=0
snd_start=False
r=数组('h')
当num\u sndMAX\u silent:
打破
如果没有提示:
如果snd_启动:
num_silent+=1
如果未启动snd_:
num_侦听+=1
如果num_侦听>4096:
德尔r[:]
num_侦听=0
样本宽度=p.获取样本大小(格式)
stream.stop_stream()
stream.close()
p、 终止()
德尔r[0:8000]
r=标准化(r)
r=纵倾(r)
r=加上静音(r,0.5)
返回样本宽度,r
def记录到文件(路径):
“从麦克风录制并将结果数据输出到‘路径’”
样本宽度,数据=记录()

data=pack(“使用
多处理功能将
记录到
文件。Process
解决了该问题

调整

if __name__ == '__main__':
    while True:
        print("Ready!")
        recorded = datetime.now()
        recorded = "testpi1_" + recorded.strftime("%Y-%m-%d--%H-%M-%S") + ".wav"
        record_to_file("/motion/" + recorded)
        os.system("./convert-audio.py " + recorded)

if __name__ == '__main__':
    while True:
        print("Ready!")
        recorded = datetime.now()
        recorded = "testpi1_" + recorded.strftime("%Y-%m-%d--%H-%M-%S") + ".wav"
        record_to_file("/motion/" + recorded)
        os.system("./convert-audio.py " + recorded)
if __name__ == '__main__':
    while True:
        print("Ready!")
        recorded = datetime.now()
        recorded = "testpi1_" + recorded.strftime("%Y-%m-%d--%H-%M-%S") + ".wav"
        p1 = multiprocessing.Process(target=record_to_file,args=("/motion/" + recorded,))
        p1.start()
        p1.join()
        os.system("./convert-audio.py " + recorded)