问题描述
在输出模式下运行的典型PyAudio回调为:
A typical PyAudio callback operating in output mode is:
def callback(ignored, frame_count, time_info, status):
buffer = <fill and return a buffer with frame_count samples of data>
return (buffer, pyaudio.paContinue)
我还没有尝试过,但是我很确定,如果我在回调返回后立即开始修改buffer
,它将在播放数据时损坏数据-是吗?
I haven't tried it, but I'm pretty sure that if I started modifying buffer
immediately after the callback returns that it would corrupt the data as it gets played -- true?
所以问题是:有没有办法知道PyAudio何时结束播放缓冲区?如果是这样,我想创建一个缓冲池,以便在PyAudio完成缓冲后再使用它们.
So the question: Is there a way to know when PyAudio has finished playing the buffer? If so, I'd like to create a buffer pool so I can reuse buffers after PyAudio is finished with them.
(如果没有一种机制可以找出PyAudio何时用完缓冲区,我看到的唯一选择是在每个回调中分配一个新的缓冲区.也许这不是大问题.)
(If there isn't a mechanism for finding out when PyAudio has finished with a buffer, the only alternative I see is to allocate a fresh buffer at each callback. Perhaps that's not a big issue.)
推荐答案
由于回调在不同的线程中运行,因此从主线程访问buffer
从根本上是不安全的,并且您无法立即知道 回调完成后(至少在没有阻止回调的情况下,您应该尝试避免这种情况).但是,您可以循环浏览缓冲区列表,只要它们的总长度长于系统延迟,就应该合理安全...
Since the callback runs in a different thread, it's basically never safe to access your buffer
from the main thread and you cannot know immediately when the callback is finished (at least not without blocking the callback, which you should try to avoid). However, you can cycle through a list of buffers and as long as their total length is longer than the system latency you should be reasonably safe ...
在这种情况下,通常要做的是使用无锁环形缓冲区将音频数据传入和传出回调.令人遗憾的是,PortAudio的ringbuffer实现不是其共享库的一部分,并且AFAIK也不在PyAudio中可用(在sounddevice
模块中也不可用).
What's typically done in this case is to use a lock-free ringbuffer to transport audio data in and out of the callback. Sadly, PortAudio's ringbuffer implementation is not part of their shared library and AFAIK it isn't available in PyAudio either (nor in the sounddevice
module).
无论如何,Python最初并不是真正的实时音频的最佳环境,因此您将不得不承受一些限制,并且永远不会真正拥有可靠的性能和延迟很短.
Anyway, Python isn't really the best environment for doing realtime audio in the first place, so you'll have to live with some limitations and you'll never really have both reliable performance and very low latencies.
这篇关于PyAudio:什么时候可以安全地修改回调缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!