簡體   English   中英

將音頻數據從ALSA緩沖區讀取到numpy數組

[英]Reading audio data from an ALSA buffer to a numpy array

我正在嘗試從ALSA緩沖區中提取數據,以便從麥克風生成計數噪聲。 但是,當我嘗試將數據轉換為數組時,我得到的結果不正確。

以下是我的代碼的一部分:

#!/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()

結果圖像

hexdump -d將內容顯示為無符號 16位整數,而您將其轉換為帶符號的 int16 numpy數組。

嘗試轉換為'u2' (或等效地, np.uint16 )的np.uint16 ,你會看到輸出與hexdump的輸出匹配:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM