
- Python - Home
- Python - Overview
- Python - History
- Python - Features
- Python vs C++
- Python - Hello World Program
- Python - Application Areas
- Python - Interpreter
- Python - Environment Setup
- Python - Virtual Environment
- Python - Basic Syntax
- Python - Variables
- Python - Data Types
- Python - Type Casting
- Python - Unicode System
- Python - Literals
- Python - Operators
- Python - Arithmetic Operators
- Python - Comparison Operators
- Python - Assignment Operators
- Python - Logical Operators
- Python - Bitwise Operators
- Python - Membership Operators
- Python - Identity Operators
- Python - Operator Precedence
- Python - Comments
- Python - User Input
- Python - Numbers
- Python - Booleans
- Python - Control Flow
- Python - Decision Making
- Python - If Statement
- Python - If else
- Python - Nested If
- Python - Match-Case Statement
- Python - Loops
- Python - for Loops
- Python - for-else Loops
- Python - While Loops
- Python - break Statement
- Python - continue Statement
- Python - pass Statement
- Python - Nested Loops
- Python Functions & Modules
- Python - Functions
- Python - Default Arguments
- Python - Keyword Arguments
- Python - Keyword-Only Arguments
- Python - Positional Arguments
- Python - Positional-Only Arguments
- Python - Arbitrary Arguments
- Python - Variables Scope
- Python - Function Annotations
- Python - Modules
- Python - Built in Functions
- Python Strings
- Python - Strings
- Python - Slicing Strings
- Python - Modify Strings
- Python - String Concatenation
- Python - String Formatting
- Python - Escape Characters
- Python - String Methods
- Python - String Exercises
- Python Lists
- Python - Lists
- Python - Access List Items
- Python - Change List Items
- Python - Add List Items
- Python - Remove List Items
- Python - Loop Lists
- Python - List Comprehension
- Python - Sort Lists
- Python - Copy Lists
- Python - Join Lists
- Python - List Methods
- Python - List Exercises
- Python Tuples
- Python - Tuples
- Python - Access Tuple Items
- Python - Update Tuples
- Python - Unpack Tuples
- Python - Loop Tuples
- Python - Join Tuples
- Python - Tuple Methods
- Python - Tuple Exercises
- Python Sets
- Python - Sets
- Python - Access Set Items
- Python - Add Set Items
- Python - Remove Set Items
- Python - Loop Sets
- Python - Join Sets
- Python - Copy Sets
- Python - Set Operators
- Python - Set Methods
- Python - Set Exercises
- Python Dictionaries
- Python - Dictionaries
- Python - Access Dictionary Items
- Python - Change Dictionary Items
- Python - Add Dictionary Items
- Python - Remove Dictionary Items
- Python - Dictionary View Objects
- Python - Loop Dictionaries
- Python - Copy Dictionaries
- Python - Nested Dictionaries
- Python - Dictionary Methods
- Python - Dictionary Exercises
- Python Arrays
- Python - Arrays
- Python - Access Array Items
- Python - Add Array Items
- Python - Remove Array Items
- Python - Loop Arrays
- Python - Copy Arrays
- Python - Reverse Arrays
- Python - Sort Arrays
- Python - Join Arrays
- Python - Array Methods
- Python - Array Exercises
- Python File Handling
- Python - File Handling
- Python - Write to File
- Python - Read Files
- Python - Renaming and Deleting Files
- Python - Directories
- Python - File Methods
- Python - OS File/Directory Methods
- Python - OS Path Methods
- Object Oriented Programming
- Python - OOPs Concepts
- Python - Classes & Objects
- Python - Class Attributes
- Python - Class Methods
- Python - Static Methods
- Python - Constructors
- Python - Access Modifiers
- Python - Inheritance
- Python - Polymorphism
- Python - Method Overriding
- Python - Method Overloading
- Python - Dynamic Binding
- Python - Dynamic Typing
- Python - Abstraction
- Python - Encapsulation
- Python - Interfaces
- Python - Packages
- Python - Inner Classes
- Python - Anonymous Class and Objects
- Python - Singleton Class
- Python - Wrapper Classes
- Python - Enums
- Python - Reflection
- Python Errors & Exceptions
- Python - Syntax Errors
- Python - Exceptions
- Python - try-except Block
- Python - try-finally Block
- Python - Raising Exceptions
- Python - Exception Chaining
- Python - Nested try Block
- Python - User-defined Exception
- Python - Logging
- Python - Assertions
- Python - Built-in Exceptions
- Python Multithreading
- Python - Multithreading
- Python - Thread Life Cycle
- Python - Creating a Thread
- Python - Starting a Thread
- Python - Joining Threads
- Python - Naming Thread
- Python - Thread Scheduling
- Python - Thread Pools
- Python - Main Thread
- Python - Thread Priority
- Python - Daemon Threads
- Python - Synchronizing Threads
- Python Synchronization
- Python - Inter-thread Communication
- Python - Thread Deadlock
- Python - Interrupting a Thread
- Python Networking
- Python - Networking
- Python - Socket Programming
- Python - URL Processing
- Python - Generics
- Python Libraries
- NumPy Tutorial
- Pandas Tutorial
- SciPy Tutorial
- Matplotlib Tutorial
- Django Tutorial
- OpenCV Tutorial
- Python Miscellenous
- Python - Date & Time
- Python - Maths
- Python - Iterators
- Python - Generators
- Python - Closures
- Python - Decorators
- Python - Recursion
- Python - Reg Expressions
- Python - PIP
- Python - Database Access
- Python - Weak References
- Python - Serialization
- Python - Templating
- Python - Output Formatting
- Python - Performance Measurement
- Python - Data Compression
- Python - CGI Programming
- Python - XML Processing
- Python - GUI Programming
- Python - Command-Line Arguments
- Python - Docstrings
- Python - JSON
- Python - Sending Email
- Python - Further Extensions
- Python - Tools/Utilities
- Python - GUIs
- Python Advanced Concepts
- Python - Abstract Base Classes
- Python - Custom Exceptions
- Python - Higher Order Functions
- Python - Object Internals
- Python - Memory Management
- Python - Metaclasses
- Python - Metaprogramming with Metaclasses
- Python - Mocking and Stubbing
- Python - Monkey Patching
- Python - Signal Handling
- Python - Type Hints
- Python - Automation Tutorial
- Python - Humanize Package
- Python - Context Managers
- Python - Coroutines
- Python - Descriptors
- Python - Diagnosing and Fixing Memory Leaks
- Python - Immutable Data Structures
- Python Useful Resources
- Python - Questions & Answers
- Python - Interview Questions & Answers
- Python - Online Quiz
- Python - Quick Guide
- Python - Reference
- Python - Cheatsheet
- Python - Projects
- Python - Useful Resources
- Python - Discussion
- Python Compiler
- NumPy Compiler
- Matplotlib Compiler
- SciPy Compiler
Create a Voice Recorder using Python
Here, we will create an application (voice recorder) using Python that will allow the user to record voice. We will create this voice recorder application using the sounddevice library and Python.
By using the voice recorder, you can initiate the recording process, pause it or, if necessary, cancel. The recorded audio is saved in two formats WAV and WAVIO. This voice recorder application can be useful for such application that needs only plain audio record and playback.
Required Libraries
To create voice recorder in Python, the following are the required libraries −
- sounddevice − The sounddevice library will be used for capturing audio.
- scipy − This library will be used for writing WAV files using write.
- wavio − This library will be used for writing wav files with other options.
- numpy − This library will be used for matrices or array calculations.
Installation
To install the required libraries to create voice records, you need to install these libraries using the PIP. Use the following statement to install all of the required libraries at once −
pip install sounddevice scipy wavio numpy
Steps to Create a Voice Recorder
1. Import Libraries
After the installation, you need to import all libraries in the code. To import the required libraries, use the following code statements −
import sounddevice as sd from scipy.io.wavfile import write import wavio as wv import numpy as np import threading
Step 2: Initialize Variables
Use the following code to set up the sampling frequency and flags for managing the recording state −
- To set sampling frequency −
freq = 44100
- To store the recorded audio segments −
recording = []
- Set the default flag value to check whether recording is active or not −
is_recording = False
- Set the default flag value to stop recording −
stop_recording = False
Step 3: Define Recording Function
Create a function to handle audio recording in a loop, appending each segment to the recording list. Use the following code −
def record_audio(): global recording, is_recording, stop_recording is_recording = True while is_recording and not stop_recording: recording_segment = sd.rec(int(freq), samplerate=freq, channels=2) sd.wait() # Wait until the recording is finished recording.append(recording_segment)
Step 4: Define Input Handling Function
Implement a function to process user commands for recording control (start, pause, stop). Use the following code −
def handle_input(): global is_recording, stop_recording while True: user_input = input("r to START , p to PAUSE and s to STOP the recording, please choice accordingly \n Enter command: ").lower() if user_input == 'p': if is_recording: print("Recording Paused, (you can again start the recording using 'r')") is_recording = False else: print("Recording is not active.") elif user_input == 'r': if not is_recording: print("Recording Resumed (type 'p' to pause or 's' to stop)") threading.Thread(target=record_audio).start() else: print("Already recording.") elif user_input == 's': if is_recording: print("Stopping recording. Thank you for recording :)") is_recording = False stop_recording = True break else: print("Nothing to stop.")
Step 5: Combine and Save Recordings
After stopping the recording, combine all recorded segments into a single audio file and save it in different formats. Use the following code −
if recording: final_recording = np.concatenate(recording, axis=0) write("recording0.wav", freq, final_recording) wv.write("recording1.wav", final_recording, freq, sampwidth=2) print("Recording saved as 'recording0.wav' and 'recording1.wav'.") else: print("No recording was made.")
Python Code to Create a Voice Recorder
Here is the complete code to create a voice recorder application in Python −
import sounddevice as sd from scipy.io.wavfile import write import wavio as wv import numpy as np import threading # Sampling frequency freq = 44100 # Initialize recording variables recording = [] is_recording = False stop_recording = False def record_audio(): global recording, is_recording, stop_recording is_recording = True while is_recording and not stop_recording: recording_segment = sd.rec(int(freq), samplerate=freq, channels=2) sd.wait() recording.append(recording_segment) def handle_input(): global is_recording, stop_recording while True: user_input = input("r to START , p to PAUSE and s to STOP the recording, please choice accordingly \n Enter command: ").lower() if user_input == 'p': if is_recording: print("Recording Paused, (you can again start the recording using 's') ") is_recording = False else: print("Recording is not working activly.") elif user_input == 'r': if not is_recording: print("Recording Resumed (type 'p' to pause or 's' to stop)") threading.Thread(target=record_audio).start() else: print("Already recording.") elif user_input == 's': if is_recording: print("Stopping recording. Thank you for recording :) ") is_recording = False stop_recording = True break else: print(" Nothing to stop.") # Start the input handler in a separate thread input_thread = threading.Thread(target=handle_input) input_thread.start() # Wait for the input thread to complete input_thread.join() # Combine all the recorded segments if recording: final_recording = np.concatenate(recording, axis=0) write("recording0.wav", freq, final_recording) wv.write("recording1.wav", final_recording, freq, sampwidth=2) print("Recording saved as 'recording0.wav' and 'recording1.wav'.") else: print("No recording was made.")
Output
After run this code you will see press "r" to start the recording, p to paused and s to stop the recording.

Now you can also see your recording audio file in your pc −

After that you can successfully listen your audio file −

Code Explanation
- Import Libraries − Import libraries for recording and processing audio as well as managing audio files.
- Initialize Variables − ‘Sampling rate’, ‘Recording list’ and ‘Flags’ as Recording control parameters should be set.
- Define record_audio Function − Records audio segments and adds it to the list.
- Define handle_input Function − Operates user’s instructions for beginning or stopping the recording process.
- Start Input Handling Thread − Manages the input handling function in a thread so that the game does not freeze.
- Wait for Input Thread to Complete − Waits for the input thread to complete the execution before proceeding with further operations of the main thread.
- Combine Recorded Segments − Combines all the recorded audio segments into one track or cue as they are called.
- Save Recording in WAV Format − Saves the combined audio as WAV files by two methods.
- Print Completion Message − Lets the users know that the recordings have been successfully saved.
- Handle No Recording Scenario − This one gives out an alarm if no audio was recorded.