2016-09-26 114 views
1

我试图从ALSA缓冲区中提取数据,以便从麦克风中产生计数噪声。但是,当我尝试将数据转换为数组时,我得到的结果不正确。将音频数据从ALSA缓冲区读取到numpy阵列

下面是我的代码部分:

#!/usr/bin/env python 

from __future__ import print_function 

import alsaaudio 
import numpy 

card = 'default' 
buf = [64] 
numpy.set_printoptions(threshold=numpy.inf) 

stream = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, card) 
stream.setchannels(1) 
stream.setrate(44100) 
stream.setformat(alsaaudio.PCM_FORMAT_S16_LE) 
stream.setperiodsize(64) 
def listen(): 
    print("Listening") 
    while True: 
     try: 
      l, data = stream.read() 

      f = open('test.raw', 'wb') 
      if l: 
       f.write(data) 
       f.close() 
     except IOError, e: 
      error_count += 1 
      print(" (%d) Error recording: %s" % (error_count, e)) 
     else: 
      decoded_block = numpy.frombuffer(data, dtype='i2') 
      print('Array PCM: \n',decoded_block) 

      return 0 

listen() 

Image with result

回答

0

hexdump -d显示内容无符号 16位整数,而你将其转换为签署 INT16 numpy的阵列。

尝试转换的'u2'一个D型(或相当于np.uint16),你会看到输出匹配hexdump的:

print(np.array([-7, -9, -10, -6, -2], dtype=np.uint16)) 
# [65529 65527 65526 65530 65534] 
+0

ali_m你有权利,但这个不会有问题。我试图找到问题,为什么从alsa得到错误的数据。 – Bednar

+0

你怎么知道你得到“错误的数据”?你期望得到什么样的价值? –

+0

我期望范围int16的数据签署了-32,768到32,767。我不知道什么是错的。可能是我的麦克风不能正常工作。 – Bednar