Advertisement
Guest User

Untitled

a guest
Mar 30th, 2020
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. import pyaudio
  2. import wave
  3.  
  4. chunk = 1024 # Record in chunks of 1024 samples
  5. sample_format = pyaudio.paInt16 # 16 bits per sample
  6. channels = 2
  7. fs = 44100 # Record at 44100 samples per second
  8. seconds = 3
  9. filename = "output.wav"
  10.  
  11. p = pyaudio.PyAudio() # Create an interface to PortAudio
  12.  
  13. print('Recording')
  14.  
  15. stream = p.open(format=sample_format,
  16. channels=channels,
  17. rate=fs,
  18. frames_per_buffer=chunk,
  19. input=True)
  20.  
  21. frames = [] # Initialize array to store frames
  22.  
  23. # Store data in chunks for 3 seconds
  24. for i in range(0, int(fs / chunk * seconds)):
  25. data = stream.read(chunk)
  26. frames.append(data)
  27.  
  28. # Stop and close the stream
  29. stream.stop_stream()
  30. stream.close()
  31. # Terminate the PortAudio interface
  32. p.terminate()
  33.  
  34. print('Finished recording')
  35.  
  36. # Save the recorded data as a WAV file
  37. wf = wave.open(filename, 'wb')
  38. wf.setnchannels(channels)
  39. wf.setsampwidth(p.get_sample_size(sample_format))
  40. wf.setframerate(fs)
  41. wf.writeframes(b''.join(frames))
  42. wf.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement