How to read realtime microphone audio volume in python and ffmpeg or similar
<p>I'm trying to read, in <em>near-realtime</em>, the volume coming from the audio of a USB microphone in Python. </p>

<p>I have the pieces, but can't figure out how to put it together. </p>

<p>If I already have a .wav file, I can pretty simply read it using <strong>wavefile</strong>:</p>

<pre><code>from wavefile import WaveReader

with WaveReader("/Users/rmartin/audio.wav") as r:
    for data in r.read_iter(size=512):
        left_channel = data[0]
        volume = np.linalg.norm(left_channel)
        print volume
</code></pre>

<p>This works great, but I want to process the audio from the microphone in real-time, not from a file.</p>

<p>So my thought was to use something like ffmpeg to PIPE the real-time output into WaveReader, but my Byte knowledge is somewhat lacking. </p>

<pre><code>import subprocess
import numpy as np

command = ["/usr/local/bin/ffmpeg",
            '-f', 'avfoundation',
            '-i', ':2',
            '-t', '5',
            '-ar', '11025',
            '-ac', '1',
            '-acodec','aac', '-']

pipe = subprocess.Popen(command, stdout=subprocess.PIPE, bufsize=10**8)
stdout_data = pipe.stdout.read()
audio_array = np.fromstring(stdout_data, dtype="int16")

print audio_array
</code></pre>

<p>That looks pretty, but it doesn't do much. It fails with a <strong>[NULL @ 0x7ff640016600] Unable to find a suitable output format for 'pipe:'</strong> error. </p>

<p>I assume this is a fairly simple thing to do given that I only need to check the audio for volume levels. </p>

<p>Anyone know how to accomplish this simply? FFMPEG isn't a requirement, but it does need to work on OSX &amp; Linux. </p>