Introduction
Sound recording systems are becoming increasingly common in a variety of industries, from simple sound documentation to complex audio processing. Making sound recordings with Python is straightforward, thanks to the sound tool library and a few other necessary modules. In this tutorial, we will primarily be using Python for voice recording. Whether you’re a beginner or an experienced developer, you’ll find this project a great way to put your skills to use.
Prerequisites
Before diving into the code, you need to have Python installed on your system. Along with that, you will need to install the following libraries:
- sounddevice: This module allows you to play and record audio.
- scipy or wavio: These libraries are used to store audio recordings as files.
Installation
Run the following commands to install the required libraries:
pip install sounddevice
pip install scipy
pip install wavio
Getting Started: Code Walkthrough
First, import the required libraries:
import sounddevice as sd
from scipy.io.wavfile import write
import wavio as wv
Setting Up the Variables
Before we start recording, we need to set two main variables.
- Sampling Frequency (freq): This determines the number of samples recorded per second. Typical frequencies are 44100 Hz or 48000 Hz.
- Recording duration (duration): Specifies the recording duration in seconds.
# Sampling frequency
freq = 44100
# Recording duration in seconds
duration = 5
Recording Audio
Once we have the variables set up, we can start recording. The sd.rec() function captures the audio and stores it in a NumPy array. The Channels parameter indicates whether the recording is in mono (1) or stereo (2).
# Start the recorder
recording = sd.rec(int(duration * freq), samplerate=freq, channels=2)
# Wait until the recording is finished
sd.wait()
Saving the Audio File
You can use the scipy or wavio libraries to store audio recordings. Both provide easy ways to save audio as .wav files.
Using Scipy:
write("recording0.wav", freq, recording)
Using Wavio:
wv.write("recording1.wav", recording, freq, sampwidth=2)
Complete Python Code
Here are the complete program rules.
import sounddevice as sd
from scipy.io.wavfile import write
import wavio as wv
# Sampling frequency
freq = 44100
# Recording duration
duration = 5
# Start recorder with the given values
recording = sd.rec(int(duration * freq), samplerate=freq, channels=2)
# Record audio for the given number of seconds
sd.wait()
# Save the NumPy array to an audio file
write("recording0.wav", freq, recording)
wv.write("recording1.wav", recording, freq, sampwidth=2)
Conclusion
Creating sound recordings in Python is a great starting point that introduces you to audio processing. You can further extend this functionality by adding features such as a GUI, real-time audio graphics, or advanced audio processing. This project demonstrates the versatility of Python and demonstrates how easy it is to combine libraries to achieve the desired results.