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): avoid division by zero when normalizing silence (#11101)

Ziwen Li342acf57f2ad
diff --git a/marimo/_plugins/stateless/audio.py b/marimo/_plugins/stateless/audio.py
index c33f7307be..3932dcbd0f 100644
--- a/marimo/_plugins/stateless/audio.py
+++ b/marimo/_plugins/stateless/audio.py
@@ -30,7 +30,7 @@ def convert_numpy_to_wav(
raise ValueError(
"Audio data must be between -1 and 1 when normalize=False."
)
- return max_abs_value if normalize else 1
+ return max_abs_value if normalize and max_abs_value > 0 else 1
data = np.array(data, dtype=float)
if len(data.shape) == 1:
diff --git a/tests/_plugins/stateless/test_audio.py b/tests/_plugins/stateless/test_audio.py
index fd07885530..ed3dc73650 100644
--- a/tests/_plugins/stateless/test_audio.py
+++ b/tests/_plugins/stateless/test_audio.py
@@ -1,7 +1,11 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+import base64
+import io
import sys
+import wave
+from html.parser import HTMLParser
import pytest
@@ -140,6 +144,47 @@ async def test_audio_numpy_constructor() -> None:
res = audio(data)
[email protected](not HAS_NUMPY, reason="numpy not installed")
[email protected]("channels", [1, 2])
[email protected]("normalize", [True, False])
+def test_audio_numpy_silence(channels: int, normalize: bool) -> None:
+ import numpy as np
+
+ class AudioParser(HTMLParser):
+ src: str | None = None
+
+ def handle_starttag(
+ self, tag: str, attrs: list[tuple[str, str | None]]
+ ) -> None:
+ if tag == "audio":
+ self.src = dict(attrs).get("src")
+
+ samples = 8
+ shape = (samples,) if channels == 1 else (channels, samples)
+ with np.errstate(invalid="raise", divide="raise"):
+ result = audio(np.zeros(shape), rate=44100, normalize=normalize)
+
+ parser = AudioParser()
+ parser.feed(result.text)
+ assert parser.src is not None
+ header, delimiter, encoded = parser.src.partition(",")
+ assert header.startswith("data:audio/")
+ assert header.endswith(";base64")
+ assert delimiter == ","
+ with wave.open(
+ io.BytesIO(base64.b64decode(encoded, validate=True)), "rb"
+ ) as wav:
+ assert tuple(wav.getparams()) == (
+ channels,
+ 2,
+ 44100,
+ samples,
+ "NONE",
+ "not compressed",
+ )
+ assert wav.readframes(samples) == b"\x00\x00" * channels * samples
+
+
@pytest.mark.skipif(sys.platform == "win32", reason="Failing on Windows CI")
async def test_audio_local_file(k: Kernel, exec_req: ExecReqProvider) -> None:
with open(__file__, encoding="utf-8") as f: # noqa: ASYNC230