I'm trying to pull data from an ALSA buffer in order to generate count noise from a mic. However, when I try to convert the data to an array I get an incorrect result.
Below is part of my code:
#!/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
displays the contents as unsigned 16bit integers, whereas you are converting it to a signed int16 numpy array.
Try converting to a dtype of 'u2'
(or equivalently, np.uint16
) and you'll see that the output matches that of hexdump
:
print(np.array([-7, -9, -10, -6, -2], dtype=np.uint16))
# [65529 65527 65526 65530 65534]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.