PyAudio:什么时候可以安全地修改回调缓冲区?

编程入门 行业动态 更新时间:2024-10-11 21:31:18
本文介绍了PyAudio:什么时候可以安全地修改回调缓冲区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在输出模式下运行的典型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:什么时候可以安全地修改回调缓冲区?

本文发布于:2023-11-25 15:04:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630219.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:什么时候   缓冲区   回调   PyAudio

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!