我正在使用 Python sounddevice 库来录制音频,但我似乎无法消除应该是连续音频文件之间的 ~0.25 到 ~0.5 秒的间隔。我认为这是因为文件写入占用时间,所以我学会了使用多处理和队列来分离文件写入,但它没有帮助。最令人困惑的是,日志表明 Main() 循环中的迭代几乎是无间隙的(只有 1-5 毫秒),但神秘的是,即使没有做任何其他重要的事情,audio_capture 函数所花费的时间也比预期的要长。我试图尽可能减少这篇文章的脚本。我的研究都指向了这种线程/多处理方法,所以我很困惑。
背景:Raspbian Buster 上的 3.7 我将数据划分为段,以便文件不会太大,我想编程任务必须应对这一挑战。之后我还有 4 个其他子流程在做各种事情。
日志:audio_capture 部分应该只占用 10:00
08:26:29.991 --- Start of segment #0
08:36:30.627 --- End of segment #0 <<<<< This is >0.6 later than it should be
08:36:30.629 --- Start of segment #1 <<<<< This is near gapless with the prior event
脚本:
import logging
import sounddevice
from scipy.io.wavfile import write
import time
import os
from multiprocessing import Queue, Process
# this process is a near endless loop
def main():
fileQueue = Queue()
writerProcess = Process(target=writer, args=(fileQueue,))
writerProcess.start()
for i in range(9000):
fileQueue.put(audio_capture(i))
writerProcess.join()
# This func makes an audio data object from a sound source
def audio_capture(i):
cycleNumber = str(i)
logging.debug('Start of segment #' + cycleNumber)
# each cycle is 10 minutes at 32000Hz sample rate
audio = sounddevice.rec(frames=600 * 32000, samplerate=32000, channels=2)
name = time.strftime("%H-%M-%S") + '.wav'
path = os.path.join('/audio', name)
sounddevice.wait()
logging.debug('End of segment #' + cycleNumber)
return [audio, path]
# This function writes the files.
def writer(input_queue):
while True:
try:
parameters = input_queue.get()
audio = parameters[0]
path = parameters[1]
write(filename=path, rate=32000, data=audio)
logging.debug('File is written')
except:
pass
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s.%(msecs)03d --- %(message)s', datefmt='%H:%M:%S',handlers=[logging.FileHandler('/audio/log.txt'), logging.StreamHandler()])
main()