2016-09-26 134 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