저는 PyAudio를 사용하여 오디오 소스의 활동을 감지하고 있습니다. 나는 종종 죽은 스트림에있는 각 오디오 이벤트에서 WAV 파일을 만들고 있습니다. memory_profiler를 사용하여 record_to_file() 메소드의 pack 메소드가 데이터 객체를 삭제하여 얻을 수있는 것보다 4 배 많은 양의 메모리를 사용하는 것으로 나타났습니다. VS와 프로세스를 디버깅객체를 삭제 한 후에도 메모리 누수가 발생하는 Python struct.pack
이Line # Mem usage Increment Line Contents
================================================
117 19.6 MiB 0.0 MiB @profile
118 def record_to_file(path):
119 "Records from the microphone and outputs the resulting data to 'path'"
120 22.4 MiB 2.8 MiB sample_width, data = record()
125 31.3 MiB 8.9 MiB data = struct.pack('<' + ('h'*len(data)), *data)
126 31.3 MiB 0.0 MiB print(sys.getsizeof(data))
127 31.3 MiB 0.0 MiB wf = wave.open(path, 'wb')
128 31.3 MiB 0.0 MiB wf.setnchannels(1)
129 31.3 MiB 0.0 MiB wf.setsampwidth(sample_width)
130 31.4 MiB 0.0 MiB wf.setframerate(RATE)
131 31.4 MiB 0.0 MiB wf.writeframes(data)
132 31.4 MiB 0.0 MiB wf.close()
133 30.4 MiB -0.9 MiB del data
134 27.9 MiB -2.5 MiB gc.collect()
, 나는 '시간'문자의 매우 많은 양을보고하고있다 :이 코드는 여기에
from sys import byteorder
import sys
from array import array
import struct
import gc
import pyaudio
import wave
import subprocess
import objgraph
from memory_profiler import profile
from guppy import hpy
THRESHOLD = 5000
CHUNK_SIZE = 1024
FORMAT = pyaudio.paInt16
RATE = 44100
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)"
r = array('h', [0 for i in xrange(int(seconds*RATE))])
r.extend(snd_data)
r.extend([0 for i in xrange(int(seconds*RATE))])
return r
def record():
"""g
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
snd_started = False
r = array('h')
while 1:
# little endian, signed short
snd_data = array('h', stream.read(CHUNK_SIZE))
if byteorder == 'big':
snd_data.byteswap()
r.extend(snd_data)
silent = is_silent(snd_data)
if silent and snd_started:
num_silent += 1
elif not silent and not snd_started:
snd_started = True
if snd_started and num_silent > 400:
break
sample_width = p.get_sample_size(FORMAT)
stream.stop_stream()
stream.close()
p.terminate()
#r = normalize(r)
r = trim(r)
r = add_silence(r, 0.5)
return sample_width, r
@profile
def record_to_file(path):
"Records from the microphone and outputs the resulting data to 'path'"
sample_width, data = record()
data = struct.pack('<' + ('h'*len(data)), *data)
print(sys.getsizeof(data))
wf = wave.open(path, 'wb')
wf.setnchannels(1)
wf.setsampwidth(sample_width)
wf.setframerate(RATE)
wf.writeframes(data)
wf.close()
del data
gc.collect()
if __name__ == '__main__':
count = 1
h = hpy()
f = open('heap.txt','w')
objgraph.show_growth(limit=3)
while(1):
filename = 'demo' + str(count) + '.wav'
print("please speak a word into the microphone")
record_to_file(filename)
print("done - result written to {0}".format(filename))
cmd = 'cd "C:\\Users\\bsmit568\\Desktop\\Raudio" & ffmpeg\\bin\\ffmpeg -i {0} -acodec libmp3lame {1}.mp3'.format(filename, filename)
"subprocess.call(cmd, shell=True)"
count += 1
objgraph.show_growth()
print h.heap()
Detect & Record Audio in Python에서 가져 메모리 프로파일 러 모듈에서 출력 한 반복이다 내 시스템 메모리에 누수가 발생하는 이유가 있습니다. 모든 도움을 크게 주시면 감사하겠습니다.
감사합니다. 정확히 내가 필요로하는 것. 메모리가 적 으면 자동으로 호출 할 것이라고 가정합니다. 언제든지 변경하면 무엇을 의미합니까? 코드 릴리스 사이에? –
예. 이 메소드는 라이브러리 dev에서 통지하지 않고 새 릴리스 후에 중단 될 수 있습니다. – PeterH
'_'로 시작하는 메소드는 실제로 라이브러리 외부에서 사용되지 않아야합니다. 파이썬에서는 java 나 C++과 같은 'private'메소드가 없다. 예를 들어, Java에서 누군가가 클래스의 메소드에 액세스 할 수 없게하려는 경우 개발자는이를 개인용으로 표시 할 수 있으며 언어는 메소드에 대한 액세스를 차단하지만 Python에서는 그러한 것이 없습니다. 명명 규칙이 있습니다. 메서드 이름이'_' 또는'__'로 시작하면, 개발자가 메소드가 릴리즈간에 동일하게 유지되거나 그냥 삭제되는 것을 보장하지 않기 때문에 메소드 이름이 라이브러리의 내부에서만 사용되어야합니다. – PeterH