python - pyaudio stream.close()导致程序崩溃且不能捕获到异常
问题描述
我想要频繁地使用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
相关文章:
1. css - 文字排版问题,内容都是动态抓出来的,字数不一定。如何对齐啊2. javascript - Ajax返回json格式之后的数据解析后取出来的数据为undefined?3. git - 在web应用分布式部署的情况下怎么进行配置更新4. css3 - 微信前端页面遇到的transition过渡动画的bug5. 前端 - WebStrom安装了angularjs插件,但是没有语法提示6. 网页爬虫 - 关于Python的编码与解码问题7. 微信开放平台 - ios APP能不能打开微信然后通过微信跳转到指定的URL?8. selenium-selenium-webdriver - python 将当前目录加入到 环境变量9. javascript - imgzoom插件所引发的bug血案!!!!10. php ZipArchive关于不同目录文件压缩

网公网安备