Python sound recording on detected sound

I am looking for a python script to run in the background and use pyaudio to record audio files when the microphone threshold reaches a certain point. This is for a monitor in a two way radio network. Therefore, we only want to record the transmitted sound.

Tasks:

  • Record audio input with threshold n% of shutter

  • stop recording after so many seconds of silence

  • keep recording for a few seconds after sound

  • Stage 2: entering data into the MySQL database to search for records

I am considering a file structure similar

/home/Recodings/2013/8/23/12-33.wav will be the broadcast record on 08/23/2013 @ 12: 33.wav

I used the code from

Detecting and recording sound with python

I’ve lost a little where to go from here now, and a small guide will be greatly appreciated

Thank you

+5
source share
3 answers

Some time ago I wrote a few steps

  • Record audio input on an% gate threshold

A: Run the boolean variable type for "Silence" and you can calculate RMS to decide if Silence is true or false, set one RMS threshold

  • stop recording after so many seconds of silence

A: You need to calculate one timeout to get the frame rate, chunk size and how many seconds you want to calculate the wait time (FrameRate / chunk * Max_Seconds)

  • keep recording for so many seconds after audio

A: If Silence is false == (RMS> Threshold), get the last piece of audio data (LastBlock) and just save the record :-)

  • Phase 2: input data into MySQL database to search the recordings

A: This step is up to you.

Source:

 import pyaudio import math import struct import wave #Assuming Energy threshold upper than 30 dB Threshold = 30 SHORT_NORMALIZE = (1.0/32768.0) chunk = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 16000 swidth = 2 Max_Seconds = 10 TimeoutSignal=((RATE / chunk * Max_Seconds) + 2) silence = True FileNameTmp = '/home/Recodings/2013/8/23/12-33.wav' Time=0 all =[] def GetStream(chunk): return stream.read(chunk) def rms(frame): count = len(frame)/swidth format = "%dh"%(count) # short is 16 bit int shorts = struct.unpack( format, frame ) sum_squares = 0.0 for sample in shorts: n = sample * SHORT_NORMALIZE sum_squares += n*n # compute the rms rms = math.pow(sum_squares/count,0.5); return rms * 1000 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 #I chage here (new Ident) all.append(data) print "end record after timeout"; data = ''.join(all) print "write to File"; WriteSpeech(data) silence = True Time=0 listen(silence,Time) def listen(silence,Time): 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 "hello ederwander I'm Recording...." KeepRecord(TimeoutSignal, LastBlock) Time = Time + 1 if (Time > TimeoutSignal): print "Time Out No Speech Detected" sys.exit() p = pyaudio.PyAudio() stream = p.open(format = FORMAT, channels = CHANNELS, rate = RATE, input = True, output = True, frames_per_buffer = chunk) listen(silence,Time) 
+8
source

The current top answer is a bit outdated and works only for python 2. Here is the version updated for python 3. It combines functions into classes and packs everything into one easy-to-use version. Note that there is one key difference between the main answer and my script:

The script at the top writes one file and then stops, while my script continues to write whenever a noise is detected, and writes the entries to the directory as it arrives.

The basic idea of ​​both scenarios is pretty similar:

Step 1: β€œListen” until rms gets over the threshold

Step 2. Start recording, set a timer when you want to stop recording, == TIMEOUT_LENGTH

Step 3: If the standard deviation again exceeds the threshold before the timer expires, reset the timer

Step 4. Now that the timer has expired, write the entry in the directory and return to step 1.

 import pyaudio import math import struct import wave import time import os Threshold = 10 SHORT_NORMALIZE = (1.0/32768.0) chunk = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 16000 swidth = 2 TIMEOUT_LENGTH = 5 f_name_directory = r'C:\Users\Jason\PyCharmProjects\AutoRecorder\records' class Recorder: @staticmethod 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 def __init__(self): self.p = pyaudio.PyAudio() self.stream = self.p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, output=True, frames_per_buffer=chunk) def record(self): print('Noise detected, recording beginning') rec = [] current = time.time() end = time.time() + TIMEOUT_LENGTH while current <= end: data = self.stream.read(chunk) if self.rms(data) >= Threshold: end = time.time() + TIMEOUT_LENGTH current = time.time() rec.append(data) self.write(b''.join(rec)) def write(self, recording): n_files = len(os.listdir(f_name_directory)) filename = os.path.join(f_name_directory, '{}.wav'.format(n_files)) wf = wave.open(filename, 'wb') wf.setnchannels(CHANNELS) wf.setsampwidth(self.p.get_sample_size(FORMAT)) wf.setframerate(RATE) wf.writeframes(recording) wf.close() print('Written to file: {}'.format(filename)) print('Returning to listening') def listen(self): print('Listening beginning') while True: input = self.stream.read(chunk) rms_val = self.rms(input) if rms_val > Threshold: self.record() a = Recorder() a.listen() 
+3
source

So you need the getLevel(data) function? Quick Hack:

 def getLevel(data): sqrsum = 0 for b in data: b = ord(b) sqrsum+=b*b return sqrsum 

This should increase with volume. Set the threshold accordingly through the trial version and error.

0
source

Source: https://habr.com/ru/post/952369/


All Articles