How to keep a python script open while some C code executes some thread?
I am trying to开发者_运维技巧 add non-blocking audio I/O to pyAudio.
pyAudio relies on PortAudio to do audio I/O. To do non-blocking audio in PortAudio, you define a callback function when opening an audio stream. When the audio stream is started, it will call the callback function whenever new audio data is required.
This part works. To test this I wrote a simple script that implements a callback function looking like this:
def pyAudioCallback(frameCount,inADCtime,curTime,outADCtime,userData,inp = None):
data=getData(frameCount)
return (data,0)
This callback is called whenever the audio stream needs new audio samples. However, the script does not know that the audio stream is still running and terminates whenever it is done, which, of course, terminates the audio stream also.
I can work around this issue by inserting some time.sleep()
somewhere. Audio playback will work fine while the script is sleeping. However, I would rather postpone the script's completion until the audio stream thinks it is done.
Is there a way to keep a Python session alive until certain criteria are met? Or is some wait loop the only option?
Several ways.
Create a pipe. Pass the read end to select.select()
with no timeout. Frob the write end when the audio is done.
Acquire a semaphore or mutex twice. Release it when the audio is done.
And more, which you probably won't need.
You could launch a child thread that contains the callback, and the main thread could wait-on/join the child thread until it completes.
If all you need to do is wait for the audio to complete, one solution comes from the PyAudio package itself.
After creating your stream, you can call stream.is_active()
to query the audio stream to see if it has finished.
An example of this is included in the documentation: Example: Callback Mode Audio I/O.
精彩评论