gpt4 book ai didi

python - 从回调中查找父函数的参数

转载 作者:行者123 更新时间:2023-12-01 04:54:48 25 4
gpt4 key购买 nike

如何从 callback 中找到为调用 callback 函数的函数提供的参数?

下面的代码(不完整)将启动一个调用回调函数的音频流。它使用 pyaudio。

现在,callback 函数中有硬编码的内容。我正在努力摆脱这些。

我已阅读 pyaudio 文档,但似乎无法将额外的参数传递给 callback 函数。我读过有关 inspect python 模块的内容,它的 getsourcegetouterframes 对我来说似乎很有趣,以便希望能够了解给 PlayStream 函数的参数,但这并没有给我带来任何结果。

如何在 callback 中引用 SoundGeneratorObject 参数?

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)

最佳答案

你能做这样的事情来为你传递的回调创建一个范围吗?

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))

关于python - 从回调中查找父函数的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27681011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com