如何在记录未知长度的数据时修复错误?

时间:2018-04-26 13:34:11

标签: python recursion multiprocessing ipc audio-recording

我正在尝试录制所需时间内麦克风的音频。我想通过获取用户输入来控制文件的持续时间。根据其决定,我必须停止录制并保存该文件的持续时间。

import pyaudio
import wave
from multiprocessing import Process

global flag
global frames

def try_recording(stream,RATE, CHUNK):
    while flag != 1:
        #for i in range(0,int(RATE/CHUNK*DURATION): 
        for i in range(0,int(RATE/CHUNK)):
            data = stream.read(CHUNK)
            frames.append(data)

def scan_input():
    num = input('Enter input number: ')
    if int(num) == 1:
       flag = 1
    else:
       scan_input()

if __name__=='__main__':
    FORMAT = pyaudio.paInt16
    CHANNELS = 2
    RATE = 44100
    CHUNK = 1024

    WAVE_OUTPUT_FILENAME = "file.wav"
    flag = 0

    audio = pyaudio.PyAudio()

    # start Recording
    stream = audio.open(format=FORMAT, channels=CHANNELS,
                    rate=RATE, input=True,
                    frames_per_buffer=CHUNK)
    print("recording...")
    frames = []
    #sys.setrecursionlimit(1500)
    p1 = Process(target=try_recording, args = (stream,RATE,CHUNK))
    p1.start()
    p2 = Process(target=scan_input)
    p2.start()

    #frames = try_recording(stream, RATE, CHUNK)
    print('finished recording')
    # stop Recording
    stream.stop_stream()
    stream.close()
    audio.terminate()

    waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
    waveFile.setnchannels(CHANNELS)
    waveFile.setsampwidth(audio.get_sample_size(FORMAT))
    waveFile.setframerate(RATE)
    waveFile.writeframes(b''.join(frames))
    waveFile.close()

当我以秒为单位定义时间时,我能够record个文件。现在我想扫描用户端的输入何时停止录制。所以我通过添加parallel processing来修改程序,以便同时运行两个函数。当我收到递归错误时,我尝试resolve添加sys.setrecursionlimit(1500),但结果并没有改变。

如何解决问题,以便我可以录制所需时间的音频。

更新: 错误和追溯

recording...
Traceback (most recent call last):
  File "D:/Projects/Trails/try.py", line 14, in try_recording
try_recording(stream,RATE,CHUNK)
  File "D:/Projects/Trails/try.py", line 14, in try_recording
try_recording(stream,RATE,CHUNK)
  File "D:/Projects/Trails/try.py", line 14, in try_recording
try_recording(stream,RATE,CHUNK)
  [Previous line repeated 995 more times]
  File "D:/Projects/Trails/try.py", line 9, in try_recording
     if flag == 1:
  RecursionError: maximum recursion depth exceeded in comparison

如果我将限制增加到44000 sys.setrecursionlimit(44000),代码会运行大约1秒并以错误结束

 Process finished with exit code -1073741571 (0xC00000FD)

UPDATE2:   @quamrana建议的更新代码。

这两个过程不同时工作。循环不在进程2功能之外。使用print语句进行测试我理解,在我按1之前它仅在进程1中循环,之后它将转移到第二个进程但不能扫描第一个函数的输入以结束记录。

更新3: 更新流程参数

Traceback (most recent call last):
File "D:/Projects/Trails/try.py", line 42, in <module>
p1.start()
File "C:\Program Files\Python36\lib\multiprocessing\process.py", line 105, in start
self._popen = self._Popen(self)
File "C:\Program Files\Python36\lib\multiprocessing\context.py", line 223, in _Popen
return _default_context.get_context().Process._Popen(process_obj)
File "C:\Program Files\Python36\lib\multiprocessing\context.py", line 322, in _Popen
return Popen(process_obj)
File "C:\Program Files\Python36\lib\multiprocessing\popen_spawn_win32.py", line 65, in __init__
reduction.dump(process_obj, to_child)
File "C:\Program Files\Python36\lib\multiprocessing\reduction.py", line 60, in dump
ForkingPickler(file, protocol).dump(obj)
TypeError: can't pickle _portaudio.Stream objects
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Program Files\Python36\lib\multiprocessing\spawn.py", line 105, in spawn_main
exitcode = _main(fd)
File "C:\Program Files\Python36\lib\multiprocessing\spawn.py", line 115, in _main
self = reduction.pickle.load(from_parent)
EOFError: Ran out of input

如何解决多处理pickle错误?

2 个答案:

答案 0 :(得分:1)

我假设您实际上并不需要try_recording递归,因此可以像这样重写:

def try_recording(stream,RATE, CHUNK):
    while flag != 1:
        for i in range(0,int(RATE/CHUNK)):
            data = stream.read(CHUNK)
            frames.append(data)

此外,您无法正确启动流程。他们应该是:

p1 = Process(target=try_recording, args=(stream,RATE,CHUNK))
p2 = Process(target=scan_input)

你的旗帜应该是一个共享变量:

# flag = 0
flag = multiprocessing.Value('i', 0)

答案 1 :(得分:0)

一旦try_recording进入else,您希望如何更新flag。你在这里实现了任何IPC机制。导致它进入无限循环