Advertisement
Guest User

Untitled

a guest
Oct 30th, 2014
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.40 KB | None | 0 0
  1. #!/usr/bin/python
  2. #############################################################################
  3. # This script is used to draw graphs of real-time audio input from the mic. #
  4. #############################################################################
  5.  
  6. import numpy, alsaaudio, time, wave, audioop, matplotlib.pyplot as plt
  7. from threading import Thread
  8.  
  9. # Used for grabbing the individual samples from a sound fragment captured by the microphone
  10. def get_samples(data):
  11.     return list(audioop.getsample(data, 2, i) for i in xrange(len(data) / 4))
  12.  
  13. # Thread that does the graph drawing
  14. def draw_raw_audio_thread(raw):
  15.     while True:
  16.         plt.cla() # Clears the current axes
  17.         plt.title('Raw Audio')
  18.         plt.plot(raw[-10000:]) # Plots values of the last 10000 elements (samples) of the raw audio
  19.         plt.axis([0,10000,-40000,40000]) # Axis limits ([xmin, xmax, ymin, ymax])
  20.  
  21.         plt.draw() # Draws the figure
  22.  
  23.         time.sleep(0.5) # Wait a bit before drawing again
  24.  
  25. if __name__ == "__main__":
  26.  
  27.     # Initialize audio recording device
  28.     inputaudio = alsaaudio.PCM(alsaaudio.PCM_CAPTURE,alsaaudio.PCM_NORMAL)
  29.  
  30.     # Setting attributes for the audio
  31.     inputaudio.setchannels(2) # 1-mono, 2-stereo
  32.     inputaudio.setrate(8000) # Audio sample rate (samples per second)
  33.     inputaudio.setformat(alsaaudio.PCM_FORMAT_S16_LE) # sample size - 16 bits
  34.  
  35.     # Period size - Sets the actual period size in samples. Each write should consist of
  36.     # exactly this number of samples, and each read will return this number of samples
  37.     # (unless the device is in PCM_NONBLOCK mode, in which case it may return nothing at all)
  38.     inputaudio.setperiodsize(40)
  39.  
  40.     # We will use this variable as a buffer for the audio data
  41.     raw_audio_data = []
  42.  
  43.     # Initialize the GUI
  44.     plt.ion()
  45.     plt.show()
  46.  
  47.     # Start the thread for drawing graphs
  48.     thread = Thread(target = draw_raw_audio_thread, args = (raw_audio_data, ))
  49.     thread.start()
  50.  
  51.     # Start recording audio
  52.     while True:
  53.         periodlen,data = inputaudio.read()  # Read the audio data and length of the period into variables
  54.         raw_audio_data.extend(get_samples(data)) # Add recorded samples into the buffer
  55.  
  56.         # When you have 100 000 samples in the buffer, empty the buffer (besides of last 10 000 samples)
  57.         if len(raw_audio_data) > 100000:
  58.             raw_audio_data[:] = raw_audio_data[-10000:]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement