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

标签 python callback pyaudio

如何从 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/

相关文章:

python - 在Python中比较两个数据帧值

python - 当我在 python 中播放 WAV 时,文件结束时程序不会停止,导致程序无响应

Python PyAudio,输出有点裂纹。也许是数学

javascript - Node.js 表搜索因使用中的 Promise 失败

python - 使用 PyAudio 作为振荡器删除/控制点击声音

python - 内存装饰器保存存储的值

python - 经过多次尝试后,我无法使用 Shutil.move 将文件从一个文件夹移动到另一个文件夹

python - 获取用Python Zelle图形绘制的图形的坐标颜色

javascript - HTML5 数据库 - 事务 VS executeSql 回调顺序

JQuery Animate 回调在动画完成之前触发