Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pyaudio
- import math
- import struct
- import wave
- import time
- import os
- import threading
- #modify this param for decibels
- ThresholdStart = 250
- ThresholdEnd = 100
- # lenght of sound
- #current interval can detect dog bark
- SOUND_LENGTH_MIN = 0.25
- SOUND_LENGTH_MAX = 0.35
- #modify this param for timeout after sound
- TIMEOUT_LENGTH = 0.05
- #modify this for how many time to replay
- Replay = 1
- # Audio settings
- SHORT_NORMALIZE = (1.0/32768.0)
- chunk = 512
- FORMAT = pyaudio.paInt16
- CHANNELS = 1
- RATE = 16000
- swidth = 2
- #audio heard will be stored here
- rec = []
- # this will compute the power of the sound
- def rms(frame):
- count = len(frame) / swidth
- format = "%dh" % (count)
- shorts = struct.unpack(format, frame)
- sum_squares = 0.0
- for sample in shorts:
- n = sample * SHORT_NORMALIZE
- sum_squares += n * n
- rms = math.pow(sum_squares / count, 0.5)
- return rms * 1000
- # this will record after detection
- def record(data):
- print('Sound detected, recording beginning')
- lrec = [data]
- start = current = time.time()
- end = time.time() + TIMEOUT_LENGTH
- while current <= end:
- data = stream.read(chunk)
- myrms = rms(data)
- if myrms >= ThresholdEnd: end = time.time() + TIMEOUT_LENGTH
- current = time.time()
- lrec.append(data)
- if SOUND_LENGTH_MIN <= current - start <= SOUND_LENGTH_MAX :
- print('Sound added')
- rec.append(lrec)
- print ("time ", time.time() - start)
- print('End sound')
- #this will play the detected sound
- def play(playevent):
- while True:
- # wait until there is something to play
- playevent.wait()
- playevent.clear()
- while rec :
- lrec = rec.pop(0)
- for i in range(Replay):
- for f in lrec:
- stream.write(f)
- #start the player thread
- playevent = threading.Event()
- threading.Thread(target=play, args=[playevent],daemon=True).start()
- # init pyaudio
- p = pyaudio.PyAudio()
- stream = p.open(format=FORMAT,
- channels=CHANNELS,
- rate=RATE,
- input=True,
- output=True,
- frames_per_buffer=chunk)
- print('Listening beginning')
- while True:
- # get sound
- input = stream.read(chunk)
- # compute power
- rms_val = rms(input)
- # then start recording if we met our power we want
- if rms_val > ThresholdStart:
- record(input)
- playevent.set()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement