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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With