如何在callback
内找到为调用callback
函数的函数提供的参数?
以下代码(不完整)将启动一个调用回调函数的音频流。它使用pyaudio。
目前,callback
功能中存在硬编码内容。我正试图摆脱那些。
我已经阅读了pyaudio doc,我似乎无法将额外的参数传递给callback
函数。我已经阅读了inspect
python模块,它的getsource
或getouterframes
对我来说似乎很有趣,以便有希望得到PlayStream
给出的论点功能,但这导致我无处可去。
如何在SoundGeneratorObject
内引用callback
参数?
谢谢。
def PlayStream(SoundGeneratorObject):
p = pyaudio.PyAudio()
stream = p.open(format = p.get_format_from_width(SoundGeneratorObject.WIDTH),
channels = SoundGeneratorObject.CHANNELS,
rate = SoundGeneratorObject.BITRATE,
frames_per_buffer = SoundGeneratorObject.CHUNKSIZE,
output = True,
stream_callback = callback)
stream.start_stream()
while stream.is_active():
time.sleep(0.1)
stream.stop_stream()
stream.close()
p.terminate()
def callback(in_data, frame_count, time_info, status_flags):
signal = waves.next()
return (signal, pyaudio.paContinue)
waves = SoundGenerator()
PlayStream(waves)
答案 0 :(得分:1)
你能做这样的事情来为你传递的回调创建一个范围吗?
def callback_maker(waves):
def callback(in_data, frame_count, time_info, status_flags):
# do stuff (waves is in scope)
signal = waves.next()
return (signal, pyaudio.paContinue)
return callback
如果可以,请按照以下方式使用:
stream = p.open(format = p.get_format_from_width(SoundGeneratorObject.WIDTH),
channels = SoundGeneratorObject.CHANNELS,
rate = SoundGeneratorObject.BITRATE,
frames_per_buffer = SoundGeneratorObject.CHUNKSIZE,
output = True,
stream_callback = callback_maker(SoundGeneratorObject))
答案 1 :(得分:1)
虽然答案已被接受,但我想通过使用 inspect 和 globals()从技术上如何通过父函数访问参数来展示替代方法。 ,这个样本将起作用:
import inspect
# as argument
SoundGeneratorObject = 'Hello World'
def PlayStream(SoundGeneratorObject):
a, b, c = 8, 9, 10
print "do a callback"
callback(a, b, c)
def callback(a, b, c):
print a, b, c
# inspect.stack[1][3] can get the function name that called the callback
# inner globals then access to the function by its name
# func_code.co_varnames will then get the argument name from the function
# since you only have 1 argument, that's why I use index [0]
# the outer globals will then access the argument value by its name
print globals()[globals()[inspect.stack()[1][3]].func_code.co_varnames[0]]
# call the parent function
PlayStream(SoundGeneratorObject)
do a callback
8 9 10
Hello World # successfully get the argument value