Reading audio data from an ALSA buffer to a numpy array
<p>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.</p>

<p>Below is part of my code:</p>

<pre><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()
</code></pre>

<p><img src="http://i.stack.imgur.com/v9o3n.jpg" alt="Image with result"></p>

<p><code>hexdump -d</code> displays the contents as <em>unsigned</em> 16bit integers, whereas you are converting it to a <em>signed</em> int16 numpy array.</p>

<p>Try converting to a dtype of <code>'u2'</code> (or equivalently, <code>np.uint16</code>) and you'll see that the output matches that of <code>hexdump</code>:</p>

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

python arrays numpy alsa