Python Forum
[PyQt] Assign Label Text as number in Hz
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyQt] Assign Label Text as number in Hz
#1
I'm totally new to this sound-involving programming, so I have this entrusted project to me, and they want my sound visualizer program can also showing frequency detail of the sound (in realtime) in number (Hz).

I have to put this number (Hz) info alone like in their own window, not in the same as my sound visualizer graph (using graph in PyQt4 promoted to pyqtgraph). Confused

This code below is the sound graph
import pyaudio
import time
import numpy as np
import threading

def getFFT(data,rate):
    """Given some data and rate, returns FFTfreq and FFT (half)."""
    data=data*np.hamming(len(data))
    fft=np.fft.fft(data)
    fft=np.abs(fft)
    #fft=10*np.log10(fft)
    freq=np.fft.fftfreq(len(fft),1.0/rate)
    return freq[:int(len(freq)/2)],fft[:int(len(fft)/2)]

class SWHear():
    def __init__(self,device=None,rate=None,updatesPerSecond=10):
        self.p=pyaudio.PyAudio()
        self.chunk=4096 # gets replaced automatically
        self.updatesPerSecond=updatesPerSecond
        self.chunksRead=0
        self.device=device
        self.rate=rate

    ### SYSTEM TESTS

    def valid_low_rate(self,device):
        """set the rate to the lowest supported audio rate."""
        for testrate in [44100]:
            if self.valid_test(device,testrate):
                return testrate
        print("SOMETHING'S WRONG! I can't figure out how to use DEV",device)
        return None

    def valid_test(self,device,rate=44100):
        """given a device ID and a rate, return TRUE/False if it's valid."""
        try:
            self.info=self.p.get_device_info_by_index(device)
            if not self.info["maxInputChannels"]>0:
                return False
            stream=self.p.open(format=pyaudio.paInt16,channels=1,
               input_device_index=device,frames_per_buffer=self.chunk,
               rate=int(self.info["defaultSampleRate"]),input=True)
            stream.close()
            return True
        except:
            return False

    def valid_input_devices(self):
        """
        See which devices can be opened for microphone input.
        call this when no PyAudio object is loaded.
        """
        mics=[]
        for device in range(self.p.get_device_count()):
            if self.valid_test(device):
                mics.append(device)
        if len(mics)==0:
            print("no microphone devices found!")
        else:
            print("found %d microphone devices: %s"%(len(mics),mics))
        return mics

    ### SETUP AND SHUTDOWN

    def initiate(self):
        """run this after changing settings (like rate) before recording"""
        if self.device is None:
            self.device=self.valid_input_devices()[0] #pick the first one
        if self.rate is None:
            self.rate=self.valid_low_rate(self.device)
        self.chunk = int(self.rate/self.updatesPerSecond) # hold one tenth of a second in memory
        if not self.valid_test(self.device,self.rate):
            print("guessing a valid microphone device/rate...")
            self.device=self.valid_input_devices()[0] #pick the first one
            self.rate=self.valid_low_rate(self.device)
        self.datax=np.arange(self.chunk)/float(self.rate)
        msg='recording from "%s" '%self.info["name"]
        msg+='(device %d) '%self.device
        msg+='at %d Hz'%self.rate
        print(msg)

    def close(self):
        """gently detach from things."""
        print(" -- sending stream termination command...")
        self.keepRecording=False #the threads should self-close
        while(self.t.isAlive()): #wait for all threads to close
            time.sleep(.1)
        self.stream.stop_stream()
        self.p.terminate()

    ### STREAM HANDLING

    def stream_readchunk(self):
        """reads some audio and re-launches itself"""
        try:
            self.data = np.fromstring(self.stream.read(self.chunk),dtype=np.int16)
            self.fftx, self.fft = getFFT(self.data,self.rate)

        except Exception as E:
            print(" -- exception! terminating...")
            print(E,"\n"*5)
            self.keepRecording=False
        if self.keepRecording:
            self.stream_thread_new()
        else:
            self.stream.close()
            self.p.terminate()
            print(" -- stream STOPPED")
        self.chunksRead+=1

    def stream_thread_new(self):
        self.t=threading.Thread(target=self.stream_readchunk)
        self.t.start()

    def stream_start(self):
        """adds data to self.data until termination signal"""
        self.initiate()
        print(" -- starting stream")
        self.keepRecording=True # set this to False later to terminate stream
        self.data=None # will fill up with threaded recording data
        self.fft=None
        self.dataFiltered=None #same
        self.stream=self.p.open(format=pyaudio.paInt16,channels=1,
                      rate=self.rate,input=True,frames_per_buffer=self.chunk)
        self.stream_thread_new()

if __name__=="__main__":
    ear=SWHear(updatesPerSecond=10) # optinoally set sample rate here
    ear.stream_start() #goes forever
    lastRead=ear.chunksRead
    while True:
        while lastRead==ear.chunksRead:
            time.sleep(.01)
        print(ear.chunksRead,len(ear.data))
        lastRead=ear.chunksRead
    print("DONE")
So my question is: how to assigned a label text so they can turn into number and keep updating while listening to the sound?
oh and code samples are most appreciated Big Grin

FYI I have done this "keep updating label text" before but in Delphy which is totally different.

Thanks in advance for any help that I receive! Blush
Reply


Messages In This Thread
Assign Label Text as number in Hz - by mekha - Jul-01-2018, 12:45 PM
RE: Assign Label Text as number in Hz - by Alfalfa - Jul-01-2018, 05:28 PM
RE: Assign Label Text as number in Hz - by mekha - Jul-01-2018, 11:12 PM
RE: Assign Label Text as number in Hz - by Alfalfa - Jul-03-2018, 04:17 PM
RE: Assign Label Text as number in Hz - by mekha - Jul-04-2018, 01:44 AM
RE: Assign Label Text as number in Hz - by mekha - Jul-07-2018, 02:44 AM
RE: Assign Label Text as number in Hz - by Alfalfa - Jul-10-2018, 04:26 PM
RE: Assign Label Text as number in Hz - by mekha - Jul-11-2018, 04:18 AM
RE: Assign Label Text as number in Hz - by DeaD_EyE - Jul-03-2018, 10:02 PM
RE: Assign Label Text as number in Hz - by mekha - Jul-07-2018, 01:14 AM
RE: Assign Label Text as number in Hz - by DeaD_EyE - Jul-04-2018, 10:30 AM
RE: Assign Label Text as number in Hz - by mekha - Jul-12-2018, 01:48 PM
RE: Assign Label Text as number in Hz - by Alfalfa - Jul-12-2018, 09:38 PM
RE: Assign Label Text as number in Hz - by mekha - Jul-16-2018, 11:39 AM
RE: Assign Label Text as number in Hz - by Alfalfa - Jul-16-2018, 12:45 PM
RE: Assign Label Text as number in Hz - by mekha - Jul-16-2018, 01:59 PM
RE: Assign Label Text as number in Hz - by Alfalfa - Jul-16-2018, 04:35 PM
RE: Assign Label Text as number in Hz - by mekha - Jul-18-2018, 12:47 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tkinter] The Text in the Label widget Tkinter cuts off the Long text in the view malmustafa 4 5,312 Jun-26-2022, 06:26 PM
Last Post: menator01
  update text variable on label with keypress knoxvilles_joker 3 5,090 Apr-17-2021, 11:21 PM
Last Post: knoxvilles_joker
  How to read text in kivy textinput or Label jadel440 1 5,390 Dec-29-2020, 10:47 AM
Last Post: joe_momma
  Tkinter: How to assign calculated value to a Label LoneStar 7 4,046 Sep-03-2020, 08:19 PM
Last Post: LoneStar
  [Kivy] Kivy text label won't shows up! AVD_01 1 3,000 Jun-21-2020, 04:01 PM
Last Post: AVD_01
  [Tkinter] Python 3 change label text gw1500se 6 4,841 May-08-2020, 05:47 PM
Last Post: deanhystad
  [Tkinter] how to update label text from list Roshan 8 5,626 Apr-25-2020, 08:04 AM
Last Post: Roshan
  [PyQt] Python PyQt5 - Change label text dynamically based on user Input ppel123 1 13,879 Mar-20-2020, 07:21 AM
Last Post: deanhystad
  [Tkinter] Label, align imported text from pandas kundrius 2 4,321 Dec-11-2019, 08:26 AM
Last Post: kundrius
  Make Label Text background (default color) transparent using tkinter in python barry76 1 24,227 Nov-28-2019, 10:19 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

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