Note - Double Click to Copy Code Contact Us!
Posts

Voice Recorder using Python

Tech Doubility
Voice Recorder using Python


  1. import pyaudio
  2. import wave
  3.  
  4. # Set the audio settings
  5. FORMAT = pyaudio.paInt16
  6. CHANNELS = 1
  7. RATE = 44100
  8. CHUNK = 1024
  9.  
  10. def start_recording():
  11. # Create an instance of PyAudio
  12. audio = pyaudio.PyAudio()
  13.  
  14. # Open the audio stream
  15. stream = audio.open(format=FORMAT,
  16. channels=CHANNELS,
  17. rate=RATE,
  18. input=True,
  19. frames_per_buffer=CHUNK)
  20.  
  21. print("Recording started. Press Ctrl+C to stop recording.")
  22.  
  23. # Create an empty list to store the recorded audio frames
  24. frames = []
  25.  
  26. try:
  27. while True:
  28. # Read audio data from the stream
  29. data = stream.read(CHUNK)
  30. frames.append(data)
  31.  
  32. except KeyboardInterrupt:
  33. # Recording stopped by pressing Ctrl+C
  34.  
  35. print("Recording stopped.")
  36.  
  37. # Close the audio stream
  38. stream.stop_stream()
  39. stream.close()
  40.  
  41. # Terminate the PyAudio instance
  42. audio.terminate()
  43.  
  44. # Save the recorded audio as a WAV file
  45. save_recording(frames)
  46.  
  47. def save_recording(frames):
  48. # Create a new WAV file for saving the recording
  49. wave_file = wave.open("recording.wav", "wb")
  50.  
  51. # Set the audio parameters for the WAV file
  52. wave_file.setnchannels(CHANNELS)
  53. wave_file.setsampwidth(pyaudio.get_sample_size(FORMAT))
  54. wave_file.setframerate(RATE)
  55.  
  56. # Write the audio frames to the WAV file
  57. wave_file.writeframes(b"".join(frames))
  58.  
  59. # Close the WAV file
  60. wave_file.close()
  61.  
  62. print("Recording saved as recording.wav")
  63.  
  64. # Start the recording
  65. start_recording()
  66.  
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.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.