Lior Dahan
Lior Dahan

Reputation: 762

Python - recording and playing microphone input

I am working on an app that receives audio from the user (with a microphone) and plays it back. Does anyone have a way/module that can store audio as an object (not as a .wav/.mp3) from a microphone?

Btw, it's on Windows, if it matters.

Thank you all for your help!

Upvotes: 1

Views: 10329

Answers (1)

Anil_M
Anil_M

Reputation: 11453

pyaudio can be used to store audio as an stream object.

On windows you can install pyaudio as python -m pip install pyaudio

Here is an example taken from pyaudio site which takes audio from microphone for 5 seconds duration then stores audio as stream object and plays back immediately .

You can modify to store stream object for different duration, manipulate then play it back. Caution: Increase in duration will increase memory requirement.

"""
PyAudio Example: Make a wire between input and output (i.e., record a
few samples and play them back immediately).
"""

import pyaudio

CHUNK = 1024
WIDTH = 2
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5

p = pyaudio.PyAudio()

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

print("* recording")

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)  #read audio stream
    stream.write(data, CHUNK)  #play back audio stream

print("* done")

stream.stop_stream()
stream.close()

p.terminate()

Upvotes: 4

Related Questions