0

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()
  • 1
    From the description of the return value in [the `numpy.append` docstring](https://docs.scipy.org/doc/numpy/reference/generated/numpy.append.html): "A copy of arr with values appended to axis. Note that append does not occur in-place: a new array is allocated and filled." Also take a look at http://stackoverflow.com/questions/13506122/how-to-use-the-function-numpy-append – Warren Weckesser Nov 28 '16 at 18:26

1 Answers1

1

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).

Matthias
  • 4,524
  • 2
  • 31
  • 50