使用python的模块多处理

时间:2015-02-01 13:19:53

标签: python audio input multiprocessing pyaudio

抱歉,如果之前有人询问,我检查过但无法找到问题的答案。 我正在尝试使用pyaudio使用多处理播放声音,因此我可以同时获取输入(最终来自NI板,但现在只需键盘)。我试图使用多处理模块并最终得到这个代码(gensin函数返回两个numpy数组,一个时间向量和一个' sin向量')。我是多处理和pyaudio模块的新手,所以非常感谢任何帮助:)

def play_sound(frequency,duration,sampRate):

    #generate the sin wave
    t, wave = gensin(frequency,duration,sampRate)

    #open the audio file
    p = pyaudio.PyAudio()

    #create a stream to play
    stream = p.open(format = pyaudio.paFloat32, 
                channels = 1, 
                rate = sampRate,
                output = True)


    stream.write(wave.astype(np.float32).tostring())
    p.close(stream)

frequency = 1200
duration = 0.5    
sampRate = 64000

p1 = multiprocessing.Process(target=play_sound,name='audioOut',args=(frequency,duration,sampRate))

然后我发出命令

p1.run()

它播放得很好,但我不认为我可以通过这种方式获得并发。

但是当我尝试

if __name__ == '__main__':
    p1.start()
    p1.join()

我收到以下错误:

Process play sounds:
Traceback (most recent call last):
  File "/Applications/anaconda/python.app/Contents/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
    self.run()
  File "/Applications/anaconda/python.app/Contents/lib/python2.7/multiprocessing/process.py", line 114, in run
    self._target(*self._args, **self._kwargs)
  File "<ipython-input-5-d9030c79195e>", line 13, in play_sound
    output = True)
  File "/Applications/anaconda/lib/python2.7/site-packages/pyaudio.py", line 747, in open
    stream = Stream(self, *args, **kwargs)
  File "/Applications/anaconda/lib/python2.7/site-packages/pyaudio.py", line 442, in __init__
    self._stream = pa.open(**arguments)
IOError: [Errno Internal PortAudio error] -9986

我在2013 Macbook pro上运行Yosemite,这段代码在Ipython中执行,但它在脚本python中也不起作用,我得到相同的PortAudio错误号。我尝试过台球而不是多处理,并没有改变任何东西。任何建议都会非常有帮助。谢谢 :)。

1 个答案:

答案 0 :(得分:1)

您可以使用billiard代替multiprocessing并禁用分叉:

pip install billiard

并将以下内容添加到代码顶部:

import billiard as multiprocessing
multiprocessing.forking_enable(False)