Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

fix(audio): support array protocol objects (torch.Tensor, JAX, etc.) in mo.audio (#9943)

Vitaliy280928098aa0
diff --git a/marimo/_plugins/stateless/audio.py b/marimo/_plugins/stateless/audio.py
index 141ebe75d3..4df324bb73 100644
--- a/marimo/_plugins/stateless/audio.py
+++ b/marimo/_plugins/stateless/audio.py
@@ -83,12 +83,12 @@ def get_resolved_src(
if DependencyManager.numpy.imported():
import numpy as np
- if isinstance(src, np.ndarray):
+ if isinstance(src, np.ndarray) or hasattr(src, "__array__"):
if rate is None:
raise ValueError(
- "rate must be specified when data is a numpy array of audio samples."
+ "rate must be specified when data is an array of audio samples."
)
- wav_data = convert_numpy_to_wav(src, rate, normalize)
+ wav_data = convert_numpy_to_wav(np.asarray(src), rate, normalize)
return mo_data.audio(wav_data).url
return io_to_data_url(src, fallback_mime_type="audio/wav")
@@ -106,7 +106,8 @@ def audio(
src: a path or URL to an audio `file`, `bytes`,
or a file-like object opened in binary mode,
`1D numpy array` → Mono waveform,
- `2D numpy array` → Multi-channel waveform (Shape: `[NCHAN, NSAMPLES]`).
+ `2D numpy array` → Multi-channel waveform (Shape: `[NCHAN, NSAMPLES]`),
+ or any array-like implementing the `__array__` protocol (e.g. `torch.Tensor`).
rate: Sampling rate (required only for NumPy arrays).
normalize: Whether to rescale NumPy array audio to its max range (`True` by default).
If `False`, values must be in `[-1, 1]`, or an error is raised.