Python Forum
Thread Rating:
  • 2 Vote(s) - 2 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Frequency Reader?
#9
I've cut the codes to simple it without the matplotlib running too, but still it's not make sense why it's always stopping in the middle of the process. And if I terminated the running file's it said if I want to close while it still running...
but actually nothing happening at all no update of the data or whatsoever

here is the updated code without the matplotlib
import pyaudio
import os
import struct
import numpy as np
import time
from time import sleep


CHUNK = 2**14 #2**15 #4096
WIDTH = 2
FORMAT = pyaudio.paInt16 
CHANNELS = 2
RATE = 44100
dt = 1.0/RATE


### frequencies of the strings for the violin (tunned in A), in Hz
f4 = 195.998   ## G3
f3 = 293.665   ## D4
f2 = 440.000   ## A4
f1 = 659.255   ## E5

n = CHUNK
freqs = np.fft.rfftfreq(n, d = dt)

def Frequency_of_position(position):
    """ Returns the frequency (Hz) of the note in from its position (halftones)
    relative to A4 in an equal tempered scale. Ex: 0 -> 440 Hz (A4), 
    12 -> 880 Hz (A5)."""
    return 440.0*(2**(1.0/12.0))**position


def Position_to_note(position):
    "A A# B C C# D D# E F F# G G#"
    SCALE = ["A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#"]
    LETTER = SCALE[position % 12]
    NUMBER = str(int((position+57) / 12))
    return LETTER+NUMBER

pos = np.array(range(-36,48))
vnote_freqs = np.vectorize(Frequency_of_position)
note_freqs = vnote_freqs(pos)


def get_frequency( spectrum ):
    return freqs[np.argmax(spectrum)]

class Freq_analysis(object):
    def __init__(self):
        self.pa = pyaudio.PyAudio()
        self.stream = self.open_mic_stream()

    def stop(self):
        self.stream.close()

    def open_mic_stream( self ):
        device_index = self.find_input_device()

        stream = self.pa.open(   format = FORMAT,
                                 channels = CHANNELS,
                                 rate = RATE,
                                 input = True,
                                 input_device_index = device_index,
                                 frames_per_buffer = CHUNK)

        return stream

    def find_input_device(self):
        device_index = None            
        for i in range( self.pa.get_device_count() ):     
            devinfo = self.pa.get_device_info_by_index(i)   
            print( "Device %d: %s"%(i,devinfo["name"]) )

            for keyword in ["mic","input"]:
                if keyword in devinfo["name"].lower():
                    print( "Found an input: device %d - %s"%    (i,devinfo["name"]) )
                    device_index = i
                    return device_index

        if device_index == None:
            print( "No preferred input found; using default input device." )

        return device_index

    def PrintFreq(self, S2):
        dominant = get_frequency( S2 )
        dist = np.abs(note_freqs-dominant)
        closest_pos = pos[np.argmin(dist)]
        closest_note = Position_to_note(closest_pos)
        print(dominant, "(",closest_note, "=",Frequency_of_position(closest_pos),")")

    def listen(self):
        try:
            block = self.stream.read(CHUNK)
        except IOError:
            # An error occurred. 
            print( "Error recording.")
            return
        indata = np.array(struct.unpack("%dh"%(len(block)/2),block))
        n = indata.size
        freqs = np.fft.rfftfreq(n, d = dt)
        data_rfft = np.fft.rfft(indata)
        S2 = np.abs(data_rfft)**2
        #self.PrintFreq(block)
        #self.update_fig(block)
        self.PrintFreq(S2)
        
if __name__ == "__main__":
    Tuner = Freq_analysis()

    for i in range(100):
        Tuner.listen()
Reply


Messages In This Thread
Frequency Reader? - by mekha - Jul-02-2018, 12:11 PM
RE: Frequency Reader? - by buran - Jul-02-2018, 12:22 PM
RE: Frequency Reader? - by mekha - Jul-02-2018, 12:26 PM
RE: Frequency Reader? - by buran - Jul-02-2018, 12:30 PM
RE: Frequency Reader? - by mekha - Jul-02-2018, 12:38 PM
RE: Frequency Reader? - by mekha - Jul-06-2018, 02:53 AM
RE: Frequency Reader? - by DeaD_EyE - Jul-06-2018, 08:29 AM
RE: Frequency Reader? - by mekha - Jul-07-2018, 02:28 AM
RE: Frequency Reader? - by mekha - Jul-11-2018, 04:04 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to optimize analog gauge reader? kadink 0 758 May-19-2023, 08:58 PM
Last Post: kadink
  vtk reader paul18fr 1 1,574 Feb-07-2022, 10:21 PM
Last Post: Larz60+
  Reset csv.reader Huck 16 20,395 Aug-01-2018, 04:20 PM
Last Post: Huck

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020