Jae Yun Yoo
Jae Yun Yoo

Reputation: 21

How to play many numpy arrays without buffering

I want to play many numpy arrays, but there are some buffering. For example,

import numpy as np
import sounddevice as sd

fs=44100
data = 0.5*np.random.uniform(-1,1,fs)
for i in range(5):
    sd.play(data, 44100)

In this case, I used just one numpy array, but want to play continuously.

Actually, I try to record sound for tens micro seconds using microphone, transform it with some applications(add sine wave...), and play the transformed data continuously.

How do I get rid of the buffering?

Upvotes: 0

Views: 252

Answers (1)

Matthias
Matthias

Reputation: 4914

If you want to record and play continuously, you should use a callback function. Have a look at the example in the documentation, I'm repeating it here:

import sounddevice as sd
duration = 5.5  # seconds

def callback(indata, outdata, frames, time, status):
    if status:
        print(status)
    outdata[:] = indata

with sd.Stream(channels=2, callback=callback):
    sd.sleep(int(duration * 1000))

This example just copies the input buffer to the output buffer, but you can of course manipulate the signal arbitrarily before assigning it back to the output.

If any of your processing relies on a fixed block size, you should explicitly set a block size in the sd.Stream() constructor, e.g. blocksize=1024.

And don't forget to always check the status argument, because if you do too much work in the callback (or if the block size is too small), this informs you if any buffer over-/underruns are happening.

Upvotes: 1

Related Questions