user6710871
user6710871

Reputation: 11

Python Sounddevice callback not appending

I am using a library in Python called SoundDevice. I am trying to record a NumPy array of undefined length. Using some example code that does the same thing with a Queue object I have rewritten the callback using append from numpy. The data appears to be there in callback, but for reasons unclear to me append is not writing to the array. At the end of the test I get the original empty array.

Here is the code:

import numpy as np
import sounddevice as sd


fs = 44100
sd.default.samplerate = fs
sd.default.device = 10


x = np.array([],ndmin = 2)

def Record():

    def callback(indata,frames,time,status):
        if status:
          print(status,flush=True)
        np.append(x,indata.copy())


    with sd.InputStream(fs,10,channels=1,callback = callback):
        print("Recording started...")


def StopRec():
    sd.stop()
    print("Recording stopped.")
    print(x) 


Record()

for i in range(10):
    pass

StopRec()

Upvotes: 0

Views: 1282

Answers (1)

Matthias
Matthias

Reputation: 4884

The main issue with your code is that you are immediatly exiting from the with statement. At the beginning of the code block inside the with statement, the method start() is called on the InputStream, in the end of it, the method stop(). Since the code block only contains one call to print() (which will return quite quickly), you are not recording anything (or probably one audio block if you are lucky).

The call to sd.stop() doesn't have any effect, because this stops only play(), rec() and playrec() calls. If you use one of the stream classes directly, you have to take care of calling start() and stop() on the stream (e.g. by using a with statement).

Upvotes: 1

Related Questions