Example #1
0
def listen(FORMAT=pyaudio.paInt16, CHUNK=2**13, FS=48000, CHANNEL=1):
    succeeded = 1
    A_NUMERATOR, A_DENOMINATOR = spl.A_weighting(FS)
    pa = pyaudio.PyAudio()
    stream = pa.open(format=FORMAT,
                     channels=CHANNEL,
                     rate=FS,
                     input=True,
                     frames_per_buffer=CHUNK)
    global prevdB
    print("Listening")
    counter = 0
    sum2 = 0
    rms = 0
    client.loop_start()  #mqtt start
    while True:
        try:
            block = stream.read(CHUNK)
        except IOError as e:
            succeeded = 0
            break
        else:
            decoded_block = numpy.fromstring(
                block, 'Int16')  # use numpy to decode the data
            filtered = lfilter(A_NUMERATOR, A_DENOMINATOR,
                               decoded_block)  # a-weighted
            for value in filtered:
                sum2 += value * value  # sum squared
                counter += 1  # count the number of samples for the average
                if counter >= FS:  #FS samples = 1s of data
                    ms = sum2 / float(FS)  # mean squared
                    rms = numpy.sqrt(ms)  # root mean squared
                    prevdB = float("{:.2f}".format(20 * numpy.log10(rms)))
                    text = float(prevdB) - float(dBOffset)
                    #		    try:
                    #		     	    for i in range (int(olddB), int(text), int((text-olddB)/3)): ##if not on rpizero, can use this commented code
                    updateLEDs(
                        text
                    )  ##and change 'text' to 'i' to make it fade between
                    #		    except:								 ##the old and new dB value. change 3 to liking.
                    #			1+1								 ##doesnt work on rpizero because not enough power.
                    print(text)
                    client.publish(directory, text)
                    counter, sum2 = 0, 0

    print("stopping")
    if succeeded:
        stream.stop_stream()
        stream.close()
    pa.terminate()
Example #2
0
class MicUSB:
    #CHUNKS[1] was 9600
    CHUNKS = [4096, 1024]
    CHUNK = CHUNKS[1]
    FORMAT = pyaudio.paInt16
    CHANNEL = 1
    #RATES[1] was 48000
    RATES = [44300, 44100]
    RATE = RATES[1]

    NUMERATOR, DENOMINATOR = spl.A_weighting(RATE)

    def __init__(self):
        self.__pa = pyaudio.PyAudio()
        self.__stream = self.__pa.open(format=MicUSB.FORMAT,
                                       channels=MicUSB.CHANNEL,
                                       rate=MicUSB.RATE,
                                       input=True,
                                       frames_per_buffer=MicUSB.CHUNK)
        self.__currentdB = 0
        self.__Init()

    def __Init(self):
        self.__Listen(45)

    def __fire_and_forget(f):
        def wrapped(*args, **kwargs):
            return asyncio.get_event_loop().run_in_executor(
                None, f, *args, *kwargs)

        return wrapped

    @__fire_and_forget
    def __Listen(self, duration):

        endTime = time.time() + duration
        print("Listening...")
        error_count = 0
        while True:
            try:
                block = self.__stream.read(MicUSB.CHUNK,
                                           exception_on_overflow=False)
            except IOError as e:
                error_count += 1
                print(" (%d) Error recording: %s" % (error_count, e))
            else:
                decoded_block = numpy.fromstring(block, 'Int16')
                y = lfilter(MicUSB.NUMERATOR, MicUSB.DENOMINATOR,
                            decoded_block)
                self.__currentdB = 20 * numpy.log10(spl.rms_flat(y))
                #print(new_decibel)

        self.__stream.stop_stream()
        self.__stream.close()
        self.__pa.terminate()

    # def __OpenStream(self):

    def GetdB(self):
        return self.__currentdB

    def __Update_dB(self, new_dB):
        if abs(self.__currentdB - new_dB) > 2:
            self.__currentdB = new_dB
    command(0x0c)
    #usleep(39)


#main
init()
command(_clear)
writeLCD("RMS: ")

fs = 16000
channel = 1
counter = 0
size = 2**13
#size = 9600
#size = 4000
NUMERATOR, DENOMINATOR = spl.A_weighting(fs)
audio = pyaudio.PyAudio()


def adCallback(in_data, frame_count, time_info, status):
    data.append(in_data)
    global buf
    buf = np.frombuffer(in_data, dtype="int16") / 32768.0
    return (None, pyaudio.paContinue)


stream = audio.open(
    format=pyaudio.paInt16,
    channels=int(channel),
    rate=int(fs),
    input=True,
Example #4
0
   What is CHUNK? Let's say CHUNK = 4096
   math.pow(2, 12) => RATE / CHUNK = 100ms = 0.1 sec
'''
CHUNKS = [4096, 9600]  # Use what you need
CHUNK = CHUNKS[1]  # rate/chunk=50ms=0.05sec
FORMAT = pyaudio.paInt16  # 16 bit
CHANNEL = 1  # 1 means mono. If stereo, put 2
'''
update your mic rate
'''
RATES = [44300, 48000]
RATE = RATES[1]

NUMERATOR, DENOMINATOR = spl.A_weighting(
    RATE
)  # A weighting using scientific python library, converting frequencies to DB


def get_path(base, tail, head=''):
    return os.path.join(base, tail) if head == '' else get_path(
        head,
        get_path(base, tail)[1:])


BASE_DIR = os.path.dirname(os.path.abspath(__file__))
SINGLE_DECIBEL_FILE_PATH = get_path(BASE_DIR,
                                    'decibel_data/single_decibel.txt')
MAX_DECIBEL_FILE_PATH = get_path(
    BASE_DIR, 'decibel_data/max_decibel.txt'
)  # update path this txt file contains max value for db we will update this value from android app
Example #5
0
import os, errno
import pyaudio
import spl_lib as spl
from scipy.signal import lfilter
import numpy

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

CHUNK = 2**13  #8192
FORMAT = pyaudio.paInt16  # 16 bit
CHANNEL = 1

FS = 48000

# Create the filter coeffs
A_NUMERATOR, A_DENOMINATOR = spl.A_weighting(FS)
C_NUMERATOR, C_DENOMINATOR = spl.C_weighting(FS)


def get_path(base, tail, head=''):
    return os.path.join(base, tail) if head == '' else get_path(
        head,
        get_path(base, tail)[1:])


'''
Listen to mic
'''
pa = pyaudio.PyAudio()

stream = pa.open(format=FORMAT,