This is a follow-on from the post: Python record audio on detected sound
I have most of it sorted now but continue to have one bug.
After the program runs once saves one recording and enters it into the DB, it returns to print listening and waiting for speech. no matter how loud the volume then goes it doesn't record again you have to the break out of the program?
I have removed the listen()
function so now back to basics looking for a way to after the recording has finished start from the beginning and wait for next audio.
Here with the present code:
import pyaudio
import math
import struct
import wave
import datetime
import os
import sys
import MySQLdb
utc_datetime = datetime.datetime.utcnow()
FileTime = utc_datetime.strftime("%Y-%m-%d-%H%M")
#Assuming Energy threshold upper than 30 dB
Threshold = 30
SHORT_NORMALIZE = (1.0/32768.0)
chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 16000
swidth = 2
Max_Seconds = 5
TimeoutSignal=((RATE / chunk * Max_Seconds) + 2)
silence = True
FileNameTmp = '/var/www/Recordings/'+FileTime+'.wav'
FileNameWWW = 'Recordings/'+FileTime+'.wav'
Time=0
all =[]
p = pyaudio.PyAudio()
stream = p.open(format = FORMAT,
channels = CHANNELS,
rate = RATE,
input = True,
output = True,
frames_per_buffer = chunk)
# SQL DB Connection
db = MySQLdb.connect("localhost","root","*****","radiolink" )
cursor = db.cursor()
def GetStream(chunk):
return stream.read(chunk)
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
# Define What to Do When WriteSpeech is Called
def WriteSpeech(WriteData):
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(FileNameTmp, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(WriteData)
wf.close()
def KeepRecord(TimeoutSignal, LastBlock):
all.append(LastBlock)
for i in range(0, TimeoutSignal):
try:
data = GetStream(chunk)
except:
continue
all.append(data)
print "end record after timeout";
data = ''.join(all)
print "Creating File " +FileNameTmp;
WriteSpeech(data)
print "Entering Record into DB";
File = FileNameWWW
query ="""
INSERT INTO recordings
(`id`, `time`,`filename`,`active`,`status`)
VALUES
(NULL,NOW(), %s,1,1) """
cursor.execute(query,(File))
db.commit()
silence = True
Time=0
print "Listening......"
print "Waiting for Speech"
while silence:
try:
input = GetStream(chunk)
except:
continue
rms_value = rms(input)
if (rms_value > Threshold):
silence=False
LastBlock=input
print "Recording...."
KeepRecord(TimeoutSignal, LastBlock)
Time = Time + 1
if (Time > TimeoutSignal):
print "Waiting No Speech Detected"
sys.exit()