Gehe zu deutscher Webseite

ViaThinkSoft CodeLib

This article is in:
CodeLibProgramming aidsPython

#!/usr/bin/env python3

import pyaudio
import numpy as np

CHUNK = 2*4096 # number of data points to read at a time
RATE = 48000 # time resolution of the recording device (Hz)
DEVICE = 0 # default output device
TARGET_FREQ = 440 # in Hz

p = pyaudio.PyAudio()

stream=p.open(format=pyaudio.paInt16,channels=1,rate=RATE,input=True, input_device_index=DEVICE,
              frames_per_buffer=CHUNK)

col_target = []
col_other = []

while True:
    indata = np.fromstring(stream.read(CHUNK),dtype=np.int16)
    fftData=np.fft.fft(indata)
    freqs = np.fft.fftfreq(fftData.size)
    magnitudes = fftData[1:int(fftData.size/2)]

    # Find out volume of target frequency

    idx = (np.abs(freqs-TARGET_FREQ/RATE)).argmin()
    volume_target = np.sum(np.abs(magnitudes[int(idx-1):int(idx+1)])) / 3

    # Find out the general volume

    volume_other = np.mean(np.abs(magnitudes))

    # Filter peaks

    col_other.append(volume_other)
    while len(col_other) > 10:
        col_other.pop(0)
    volume_other  = (np.sum(col_other) + 5*volume_other) / 15

    col_target.append(volume_target)
    while len(col_target) > 10:
        col_target.pop(0)
    volume_target = (np.sum(col_target) + 5*volume_target) / 15

    # Check ratio

    print(volume_target/volume_other)

stream.close()
p.terminate()
Daniel Marschall
ViaThinkSoft Co-Founder