在实时Python 3.7中操作音频缓冲区

2024-04-25 17:54:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用“声音设备”库构建了一个Python3.7程序,该程序从音频设备接收缓冲区(512个样本),对其进行处理并发送到同一设备。 “音频设备”是一个声卡,因此可以连接麦克风,处理输入,并在处理后实时发送给扬声器

这个过程是立体声的(两个通道),我正在努力提高效率。它是一个简单的低通滤波器

接收缓冲区: 形状中有512个样本:

[
[XLeft1 , XRight1]
[XLeft2 , XRight2]
...
[XLeft512 , XRight512]
]

过程: 必须逐个采样,如:[Xleft1,XLeft2,…,XLeft512],然后右通道也是如此

输出缓冲区 必须与缓冲区中的相同。所以在这里,我需要做一些数据转换,我试图最小化

实现这一点的CPU效率最高的方法是什么

我现在使用的代码是:

def do_process(self,indata):
  Y=[]
  for i in range(0,len(indata[0])):                    #Two channels for stereo
      v=indata[:,i]# i represent number of channel     #v is the current channel 
      if i ==0:
       current_chunk_filter=self.low_pass1.do_calculation(v)   
      if i==1:
       current_chunk_filter=self.low_pass2.do_calculation(v)
      Y.insert(i,current_chunk_filter)
      
  outdata=list(map(list, zip(*Y)))# transpose the list
  dimensioned_numpy_array = np.reshape(outdata, (int(len(outdata)), 2)) #Makes the list vertical
  return   dimensioned_numpy_array 

我如何避免(或提高效率)从列表、转置、重塑等方面走出来


Tags: theself程序过程currentfilterdolist
1条回答
网友
1楼 · 发布于 2024-04-25 17:54:45

输出块的大小不会改变,一次只存在一个。因此,预先分配它,然后将输出数据直接放入正确的位置

比如:

channels = 2
samples = 512
out = numpy.zeros(shape=(samples, channels))
filters = [self.low_pass1, self.low_pass2]

def do_process(in, out):
  
  for channel in range(in.shape[1]):
     out[:, channel] = filter[channel].do_calculation(in[:, channel])


相关问题 更多 >