Skip to content

"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/

Python

fix(audacity): write 8-bit WAV as unsigned PCM (#387)

Syed Osama Ali Shaha92e590b0294
diff --git a/audacity/agent-harness/cli_anything/audacity/tests/test_full_e2e.py b/audacity/agent-harness/cli_anything/audacity/tests/test_full_e2e.py
index 6339f2971..a9da019e7 100644
--- a/audacity/agent-harness/cli_anything/audacity/tests/test_full_e2e.py
+++ b/audacity/agent-harness/cli_anything/audacity/tests/test_full_e2e.py
@@ -132,6 +132,19 @@ class TestWavIO:
corr = np.corrcoef(original[:min_len], loaded[:min_len])[0, 1]
assert corr > 0.99
+ def test_write_read_roundtrip_8bit(self, tmp_dir):
+ # 8-bit WAV PCM is unsigned (0..255, silence == 128). A signed encoder
+ # makes silence (0.0) read back as full-scale (-1.0). Assert every value
+ # round-trips within the 8-bit quantization step (1/128 ~= 0.0078).
+ path = os.path.join(tmp_dir, "rt8.wav")
+ original = [0.0, 0.5, 1.0, -0.5, -1.0, 0.25]
+ write_wav(path, original, 44100, 1, 8)
+ loaded, sr, ch, bd = read_wav(path)
+ assert bd == 8
+ assert len(loaded) == len(original)
+ for o, l in zip(original, loaded):
+ assert abs(o - l) < 0.02, f"{o} -> {l}"
+
def test_wav_file_properties(self, sine_wav):
with wave.open(sine_wav, "r") as wf:
assert wf.getframerate() == 44100
diff --git a/audacity/agent-harness/cli_anything/audacity/utils/audio_utils.py b/audacity/agent-harness/cli_anything/audacity/utils/audio_utils.py
index cc6e2e938..35729ddcd 100644
--- a/audacity/agent-harness/cli_anything/audacity/utils/audio_utils.py
+++ b/audacity/agent-harness/cli_anything/audacity/utils/audio_utils.py
@@ -325,7 +325,7 @@ def samples_to_wav_bytes(
sample_width = 2
elif bit_depth == 8:
max_val = 127
- fmt = "<b"
+ fmt = None # 8-bit WAV samples are unsigned; handled specially below
sample_width = 1
elif bit_depth == 24:
max_val = 8388607
@@ -345,6 +345,9 @@ def samples_to_wav_bytes(
if bit_depth == 24:
# Pack 24-bit as 3 bytes little-endian
raw.extend(struct.pack("<i", int_val)[:3])
+ elif bit_depth == 8:
+ # 8-bit WAV samples are unsigned (0..255), centered at 128
+ raw.extend(struct.pack("<B", int_val + 128))
else:
raw.extend(struct.pack(fmt, int_val))
@@ -374,7 +377,7 @@ def write_wav(
sample_width = 2
elif bit_depth == 8:
max_val = 127
- fmt = "<b"
+ fmt = None # 8-bit WAV samples are unsigned; handled specially below
sample_width = 1
elif bit_depth == 24:
max_val = 8388607
@@ -393,6 +396,9 @@ def write_wav(
int_val = max(-max_val - 1, min(max_val, int_val))
if bit_depth == 24:
raw.extend(struct.pack("<i", int_val)[:3])
+ elif bit_depth == 8:
+ # 8-bit WAV samples are unsigned (0..255), centered at 128
+ raw.extend(struct.pack("<B", int_val + 128))
else:
raw.extend(struct.pack(fmt, int_val))