Advertisement
Guest User

Untitled

a guest
Jun 6th, 2018
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.05 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3.  
  4. import pyaudio
  5. import struct
  6. import math
  7. import wave
  8. import numpy as np
  9. import matplotlib.pyplot as plt
  10. from scipy.io import wavfile
  11. #import urllib  
  12. #import urllib2
  13. import os
  14. import smtplib, getpass
  15. from email.mime.multipart import MIMEMultipart
  16. from email.mime.text import MIMEText
  17.  
  18. class Microphone:
  19.  
  20.     def rms(self,frame):
  21.         count = len(frame)/2
  22.         format = "%dh"%(count)
  23.         shorts = struct.unpack( format, frame )
  24.         sum_squares = 0.0
  25.         for sample in shorts:
  26.             n = sample * (1.0/32768.0)
  27.             sum_squares += n*n
  28.         rms = math.pow(sum_squares/count,0.5);
  29.         return rms * 1000
  30.  
  31.  
  32.     def passiveListen(self,persona):
  33.  
  34.         CHUNK = 1024; RATE = 8000; THRESHOLD = 200; LISTEN_TIME = 5
  35.  
  36.         didDetect = False
  37.  
  38.         # prepare recording stream
  39.         p = pyaudio.PyAudio()
  40.         stream = p.open(format=pyaudio.paInt16, channels=1, rate=RATE, input=True, frames_per_buffer=CHUNK)
  41.  
  42.         # stores the audio data
  43.         all =[]
  44.  
  45.         # starts passive listening for disturbances
  46.         Var_float = RATE / CHUNK * LISTEN_TIME
  47.         Var_int = RATE // CHUNK * LISTEN_TIME
  48.         for i in range(0,int(RATE / CHUNK * LISTEN_TIME)):
  49.             input = stream.read(CHUNK)
  50.             rms_value = self.rms(input)
  51.             print (rms_value)
  52.             if (rms_value > THRESHOLD):
  53.                 didDetect = True
  54.                 print ("Listening...\n")
  55.                 break
  56.  
  57.         if not didDetect:
  58.             stream.stop_stream()
  59.             stream.close()
  60.             return False
  61.  
  62.         while didDetect==True:
  63.             print ("**** Enviar email con Gmail ****")
  64.             user = "LCDT.ytb@gmail.com"
  65.             password = "joricombiomontado"
  66.            
  67.             #Para las cabeceras del email
  68.             remitente = "LCDT.ytb@gmail.com"
  69.             destinatario = "Korbatos@gmail.com"
  70.             asunto = "Detectada actividad sospechosa"
  71.             mensaje = "Se ha detectado un movimiento o sonido extraño en su habitacion. Por favor, revise la aplicacion para cerciorarse"
  72.            
  73.             #Host y puerto SMTP de Gmail
  74.             gmail = smtplib.SMTP('smtp.gmail.com', 587)
  75.            
  76.             #Protocolo de cifrado de datos utilizado por Gmail
  77.             gmail.starttls()
  78.            
  79.             #Credenciales
  80.             gmail.login(user, password)
  81.            
  82.             #Muestra la depuración de la operación de envío l=true
  83.             gmail.set_debuglevel(1)
  84.            
  85.             header = MIMEMultipart()
  86.             header['Subject'] = asunto
  87.             header['From'] = remitente
  88.             header['To'] = destinatario
  89.            
  90.             mensaje = MIMEText(mensaje, 'html') #Content-type:text/html
  91.             header.attach(mensaje)
  92.            
  93.             #Enviar email
  94.             gmail.sendmail(remitente, destinatario, header.as_string())
  95.            
  96.             #Cerrar la conexion SMTP
  97.             gmail.quit()
  98.             break
  99.  
  100.         # append all the chunks
  101.         all.append(input)
  102.         for i in range(0, 7):
  103.             data = stream.read(CHUNK)
  104.             all.append(data)
  105.  
  106.         # save the audio data  
  107.         data = ''.join(str(e) for e in all)
  108.         stream.stop_stream()
  109.         stream.close()
  110.         wf = wave.open('audio.wav', 'wb')
  111.         wf.setnchannels(1)
  112.         wf.setsampwidth(p.get_sample_size(pyaudio.paInt16))
  113.         wf.setframerate(RATE)
  114.         wf.writeframes(data)
  115.         wf.close()
  116.  
  117.         return True
  118.  
  119. if __name__ == '__main__':
  120.     mic = Microphone()
  121.     while True:
  122.         if  mic.passiveListen('ok Google'):
  123.             fs, data = wavfile.read('audio.wav')
  124.             L = len(data)
  125.             c = np.fft.fft(data) # create a list of complex number
  126.             freq = np.fft.fftfreq(L)
  127.             #freq = np.linspace(0, 1/(2L), L/2)
  128.             print (freq)
  129.             freq_in_hertz = abs(freq * fs)
  130.             plt.plot(freq_in_hertz, abs(c))
  131.             plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement