import pyaudio import wave # Set the audio settings FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100 CHUNK = 1024 def start_recording(): # Create an instance of PyAudio audio = pyaudio.PyAudio() # Open the audio stream stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) print("Recording started. Press Ctrl+C to stop recording.") # Create an empty list to store the recorded audio frames frames = [] try: while True: # Read audio data from the stream data = stream.read(CHUNK) frames.append(data) except KeyboardInterrupt: # Recording stopped by pressing Ctrl+C print("Recording stopped.") # Close the audio stream stream.stop_stream() stream.close() # Terminate the PyAudio instance audio.terminate() # Save the recorded audio as a WAV file save_recording(frames) def save_recording(frames): # Create a new WAV file for saving the recording wave_file = wave.open("recording.wav", "wb") # Set the audio parameters for the WAV file wave_file.setnchannels(CHANNELS) wave_file.setsampwidth(pyaudio.get_sample_size(FORMAT)) wave_file.setframerate(RATE) # Write the audio frames to the WAV file wave_file.writeframes(b"".join(frames)) # Close the WAV file wave_file.close() print("Recording saved as recording.wav") # Start the recording start_recording()
Save the code in a Python file (e.g., voice_recorder.py) and run it. The program will start recording audio from the default input device and save it as a WAV file named recording.wav.
To stop the recording, press Ctrl+C. The program will save the recorded audio and display a message confirming the successful save.
Please note that you need the pyaudio library installed to run this code. You can install it using the command pip install pyaudio.