Getting volume levels from PyAudio for use in Arduino
Asked Answered
D

1

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.

Deboradeborah answered 21/10, 2014 at 3:16 Comment(3)
How come this question is related with arduino?Redhot
I wanted to send the volume of the audio from my laptop's microphone through the serial port to my Arduino.Deboradeborah
I got that, but in your question there is nothing about arduino or serial port. Your question is just about python and pyaudio.Redhot
H
10

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.

Hyperbolism answered 27/10, 2014 at 0:6 Comment(1)
Thanks! I ended up using and adapting that same codebase. @HyperbolismDeboradeborah

© 2022 - 2024 — McMap. All rights reserved.