在低功耗计算机上从Python生成流畅的音频 [英] Generating smooth audio from Python on a low-powered computer

查看:98
本文介绍了在低功耗计算机上从Python生成流畅的音频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用Python编写一个简单的音频函数生成器,以在Raspberry Pi(模型2)上运行.该代码本质上是这样做的:

I am trying to write a simple audio function generator in Python, to be run on a Raspberry Pi (model 2). The code essentially does this:

  • 生成1秒钟的音频信号(例如正弦波或方波等)
  • 反复循环播放

例如:

import pyaudio
from numpy import linspace,sin,pi,int16

def note(freq, len, amp=1, rate=44100):
 t = linspace(0,len,len*rate)
 data = sin(2*pi*freq*t)*amp
 return data.astype(int16) # two byte integers

RATE = 44100
FREQ = 261.6

pa = pyaudio.PyAudio()
s = pa.open(output=True,
            channels=2,
            rate=RATE,
            format=pyaudio.paInt16,
            output_device_index=2)

# generate 1 second of sound
tone = note(FREQ, 1, amp=10000, rate=RATE)

# play it forever    
while True:
  s.write(tone)

问题在于,即使使用外部USB声卡,循环的每次迭代也会导致音频中出现滴答声".有什么办法可以避免这种情况,而不是尝试用C重写所有内容?

The problem is that every iteration of the loop results in an audible "tick" in the audio, even when using an external USB sound card. Is there any way to avoid this, rather than trying to rewrite everything in C?

我尝试使用pyaudio回调接口,但实际上听起来更糟(例如我的Pi肠胃气胀).

I tried using the pyaudio callback interface, but that actually sounded worse (like maybe my Pi was flatulent).

生成的音频需要简短,因为最终将通过外部控件对其进行动态调整,并且控件更改的延迟超过1秒只会感觉很尴尬.有没有更好的方法可以在Python代码中产生这些信号?

The generated audio needs to be short because it will ultimately be adjusted dynamically with an external control, and anything more than 1 second latency on control changes just feels awkward. Is there a better way to produce these signals from within Python code?

推荐答案

您正在听到滴答声",因为您发送的音频不连续. 261.6 Hz的一秒包含261.6个周期,因此最终剩下大约半个周期:

You're hearing a "tick" because there's a discontinuity in the audio you're sending. One second of 261.6 Hz contains 261.6 cycles, so you end up with about half a cycle left over at the end:

您将需要更改频率以使每秒有完整的周期数(例如262 Hz),更改持续时间以使它对于完整的周期数足够长,或者生成新的音频剪裁从正确阶段开始的每一秒,以适应最后一块剩下的地方.

You'll need to either change the frequency so that there are a whole number of cycles per second (e.g, 262 Hz), change the duration such that it's long enough for a whole number of cycles, or generate a new audio clip every second that starts in the right phase to fit where the last chunk left off.

这篇关于在低功耗计算机上从Python生成流畅的音频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆