5

I want to sent volume data from my laptop's audio input (just the built-in microphone in my Macbook) to Arduino with as little lag as possible.

I see that it isn't hard to capture the audio input using PyAudio, but most of the examples for that module save the audio readings into a wav or other file format. Can I just directly measure the volume as I'm reading it into PyAudio, or do I need to save it to a file and analyze that file? I don't care about any other data in the audio beyond the volume.

Much appreciated.

3
  • How come this question is related with arduino?
    – ahaltindis
    Oct 26, 2014 at 21:55
  • I wanted to send the volume of the audio from my laptop's microphone through the serial port to my Arduino.
    – John
    Oct 27, 2014 at 23:25
  • I got that, but in your question there is nothing about arduino or serial port. Your question is just about python and pyaudio.
    – ahaltindis
    Oct 27, 2014 at 23:57

1 Answer 1

9

You can read in the volume in real time. To do this, set up the recording but don't save the data, just process it. Here, I'll get the RMS value of each chunk using Python's included audioop module. (This example is just a modification of the record demo in the PyAudio webpage to include audioop.rms.)

import pyaudio
import wave
import audioop

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    rms = audioop.rms(data, 2)    # here's where you calculate the volume

stream.stop_stream()
stream.close()
p.terminate()

Of course, if you don't like RMS, audioop has other volume measures.

1
  • Thanks! I ended up using and adapting that same codebase. @tom10
    – John
    Oct 27, 2014 at 23:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.