您的位置:首页技术文章
文章详情页

python - pyaudio stream.close()导致程序崩溃且不能捕获到异常

【字号: 日期:2022-06-29 11:05:15浏览:69作者:猪猪

问题描述

我想要频繁地使用pyaudio来播放音频,虽然他不是多线程模块,但是只使用一个子线程播放,主线程控制播放的开关应该是没有问题的。但是当我使用它播放时遇到了不能解决的麻烦。

import threadingimport waveimport pyaudioimport timepa=pyaudio.PyAudio()f=wave.open(’/home/dyan/catkin_ws/src/hlf_robot/scripts/hlf_voice/my.wav’,’rb’)raw_data=f.readframes(f.getnframes())f.close()samplewidth,channels,framerate,raw_data=2,1,16000,raw_datai=0stream1=’’def test(): while True:global i,pa,stream1try: print i stream1=pa.open(format=pa.get_format_from_width(samplewidth), channels=channels, rate=framerate, output=True) stream1.write(raw_data)i+=1 print iexcept IOError,e:print eexcept Exception,e:print ebreakt0=threading.Thread(target=test)t0.start()time.sleep(3)while True: if stream1.is_active():print 'is_active' else:print 'not active' if stream1.is_stopped():print 'is_stopped' else:print 'not stopped' print stream1._is_running print stream1._stream print ’123’ try:stream1.stop_stream()print ’456’stream1.close() except Exception,e:print ebreak print ’789’ time.sleep(3)

输出是这样的,然后崩了

0#子线程循环第一次is_active#not stopped #True #stream1._is_running<_portaudio.Stream object at 0x7efd71e00cb0> #stream1._stream123 #调用stop_stream()之前456 #调用stop_stream()之后,close()之前[Errno Unanticipated host error] -9999 #子线程捕获到主线程调用stream1.stop_stream()时由stream1.write()抛出的异常IOError,忽略这个异常继续执行0#子线程stream1.write()抛出异常i+=1未执行继续循环在pa.open()之前的print

1、也就是说在调用stream1.stop_stream()后调用stream1.close()导致程序崩溃了,而且子线程和主线程都没有捕获到异常!!!!2、如果将stop_stream()后的close()注释掉短时间内没有任何问题,但是持续运行大约10分钟左右虽然不会崩溃但是再也不能继续播放。pa.open()一直抛出异常[Errno Illegal combination of I/O devices] -9993,当我关闭程序重启时pa.open()会抛出异常(’Invalid sample rate’, -9997),播放用不了了!!!

这个问题该如何解决?

暂时使用每次播放均重开一个pyaudio.Pyaudio()对象的方式解决,这大概额外使用了cpu时间10ms。持续跑了将近20个小时没出问题。

...try: self.pa=pyaudio.PyAudio()self.stream=self.pa.open(format=self.pa.get_format_from_width(samplewidth), channels=channels, rate=framerate, output=True) self.stream.write(raw_data)except IOError,e: passfinally: self.stream.close() self.pa.terminate()...

问题解答

回答1:

這裡給了一個可能解決方法(workaround),ghost commented on 30 Jul 2016

标签: Python 编程
相关文章: