Search code examples
pythoncallbackpython-sounddevice

In InputStream, what does blocksize do? (sounddevice)


I am building a guitar tuner GUI with sounddevice. This is my code for the recording part:

 def stream(self):
        if self.stream is not None:
            self.stream.close()
        self.stream = sd.InputStream(
          channels=1, callback=self.callback, blocksize=...) 
        self.stream.start()

This is callback:

# tunertools is another file with functions that compute on arrays
def callback(indata, frames, time, status):
        print(indata)
        data = indata.copy()
        yin , *others = tunertools.YIN(data, frames)
        pitch = tunertools.avg_pitch(yin)
        noteslist = {k:v for k,v in tunertools.notes()}
        note = tunertootls.quantize(pitch, noteslist.values)
        print( {v:k for (k,v) in noteslist.values()}[note] )

For now, I am printing the output in terminal. I want a new output to be printed every 4 seconds of recording. This means that every 4 seconds, the callback function should be initiated. How do I do this? More importantly, do I need to use the blocksize parameter to do this?


Solution

  • The callback function is called at a rate determined by blocksize. If you make blocksize larger, the callback will be called less often.

    If you want to obtain information at a different rate than the callback is called, you can have a look at the example plot_input.py which uses a separate function for obtaining information and a queue.Queue for communications between them.

    If you just want some code to be executed every, say, third time the callback is called, you can simply use a global counter variable and check and increment it in the callback.