Record voice from the microphone in Python with few lines of code

In this tutorial, we will learn how to record voice from the microphone in python. This can be done by using the Pyaudio module. This pyaudio helps python to record as well as play the audio.

The recorded input audio is stored in the .wav file, our output file(generated automatically).

Our first step is to download Pyaudio into our system.

Installing Pyaudio library

To install the Pyaudio library in your system run the below commands in your command prompt(windows) or terminal(mac).

command 1: pip install pyaudio
command 2: pipwin install pyaudio

 

Python code to record audio using pyaudio and wave

Step -1: Import the required libraries

import pyaudio
import wave

Step – 2: Define a pyaudio object

p = pyaudio.PyAudio()

Step – 3: Define a stream to record the audio

stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True, frames_per_buffer=1024)

This stream has a bunch of parameters like no.of channels we want, the frequency rate, and the chunk buffer size.
Note: Input = True means that we are actually sending voice into the stream.

Step – 4: Read from the stream until we get a keyboard interrupt.

frames = []
try:
    while True:
        data = stream.read(1024)
        frames.append(data)
except KeyboardInterrupt:    
    pass

stream. read() reads the audio data from the stream.

Step – 5: Terminating the recording and the session.

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

stream.stop_stream() pauses the recording
stream.close() stops the recording.
p.terminate() terminates the whole audio session.

Step – 6: Create a sound file and write the whole frameset into it.

sound_file = wave.open("output.wav","wb")
sound_file.setnchannels(1)
sound_file.setsampwidth(p.get_sample_size(pyaudio.paInt16))
sound_file.setframerate(44100)
sound_file.writeframes(b''.join(frames))
sound_file.close()

We open the sound file in byte mode cause the data is in binary.

The output is stored in the output.wav file. Play the file to listen to our recording.

 

Build a simple Sound Recorder in Python

Create an Audiobook from a PDF file using Python

Leave a Reply

Your email address will not be published.