Skip to content

fix: save_audio omits clamping before int16 conversion causing - #26

Open
andrewwhitecdw wants to merge 1 commit into
NVIDIA:mainfrom
andrewwhitecdw:bugfix/utils-save-audio-omits-clamping-before-int16
Open

fix: save_audio omits clamping before int16 conversion causing#26
andrewwhitecdw wants to merge 1 commit into
NVIDIA:mainfrom
andrewwhitecdw:bugfix/utils-save-audio-omits-clamping-before-int16

Conversation

@andrewwhitecdw

Copy link
Copy Markdown

This PR addresses the following issue in utils.py: save_audio omits clamping before int16 conversion causing.

Changes

  • utils.py: save_audio omits clamping before int16 conversion causing.

Details

--- a/utils.py
+++ b/utils.py
@@ -1,5 +1,6 @@
-def save_audio(audio, path, sr):
-    # wav: torch with 1d shape
-    audio = audio * MAX_WAV_VALUE
-    audio = audio.cpu().numpy().astype("int16")
-    write(path, sr, audio)
+def save_audio(audio, path, sr):
+    # wav: torch with 1d shape
+    audio = audio.clamp(min=-1.0, max=1.0)
+    audio = audio * MAX_WAV_VALUE
+    audio = audio.cpu().numpy().astype("int16")
+    write(path, sr, audio)

Tests

  • tests/test_utils.py
--- /dev/null
+++ b/tests/test_utils.py
@@ -0,0 +1,24 @@
+import numpy as np
+import pytest
+import torch
+from unittest.mock import patch
+
+from utils import MAX_WAV_VALUE, save_audio
+
+
+def test_save_audio_clamps_before_int16_conversion():
+    """Values outside [-1, 1] must be clipped before scaling to int16."""
+    captured = {}
+
+    def fake_write(path, sr, data):
+        captured["data"] = data
+
+    audio = torch.tensor([0.5, 1.5, -0.8, -2.0])
+    expected = audio.clamp(min=-1.0, max=1.0).numpy() * MAX_WAV_VALUE
+
+    with patch("utils.write", fake_write):
+        save_audio(audio, "/tmp/fake.wav", 22050)
+
+    np.testing.assert_array_equal(
+        captured["data"],
+        expected.astype("int16"),
+    )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant