Skip to content

np.asarray(buf) returns incorrect number of samples for multichannel buffers #19

@ashNotKetchup

Description

@ashNotKetchup

Issue: np.asarray(buf) returns incorrect number of samples for multichannel buffers

Summary

When using np.asarray(buf) on a multichannel buffer~, the resulting NumPy array does not reflect the actual number of samples expected from interleaved audio.

Reproduction

def get_samples_multichannel(buffer_name: str):
    channel_count = 2
    length = 100

    buf = api.Buffer(buffer_name, "", channels=channel_count)
    buf.framecount = length

    t = np.linspace(0, 1, length, endpoint=False, dtype=np.float32)
    xs = np.array(
        [np.sin(t * 2 * math.pi * 5) * (-1 if ch % 2 else 1)
         for ch in range(channel_count)]).T
    flattened_data = xs.reshape(-1)
    buf.set_samples(flattened_data)

    buf = api.get_buffer(buffer_name)
    api.post(f"Accessed buffer '{buffer_name}' with {buf.n_samples} samples and {buf.channelcount} dimensions")

    xs = np.asarray(buf)
    xs = np.array(xs, dtype=np.float32)
    api.post(f"Converted buffer samples to numpy array with shape: {xs.shape} and dtype: {xs.dtype}")
[''get_samples_multichannel('myBufferName')"] -> [s to_py]

Expected Output

A 2-channel, 100-frame buffer should return 200 samples when accessed as a NumPy array — either in interleaved or (frames, channels) format.

Actual Output

Accessed buffer 'myBufferName' with 200 samples and 2 dimensions **Good and expected!**
Converted buffer samples to numpy array with shape: (200,) and dtype: float32 *
  • np.asarray(buf) silently returns a flat array of unclear dimensionality

Suggestion

If possible:

  • Clarify np.asarray(buf) behaviour in the pyjs docs.
  • Consider a helper function or .to_numpy() API that guarantees correct multichannel extraction.
  • Emit a warning if np.asarray(buf) is used on a multichannel buffer, since it may silently return incomplete data.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions