diff --git a/src/agents/voice/input.py b/src/agents/voice/input.py index c39172c79a..a88722a1b3 100644 --- a/src/agents/voice/input.py +++ b/src/agents/voice/input.py @@ -19,19 +19,48 @@ def _buffer_to_audio_file( sample_width: int = 2, channels: int = 1, ) -> tuple[str, io.BytesIO, str]: + if sample_width not in {1, 2, 3, 4}: + raise UserError("Sample width must be between 1 and 4 bytes") + if buffer.dtype == np.float32: - # convert to int16 - buffer = np.clip(buffer, -1.0, 1.0) - buffer = (buffer * 32767).astype(np.int16) + clipped_buffer = np.clip(buffer, -1.0, 1.0) + if sample_width == 1: + audio_bytes = ( + np.rint((clipped_buffer.astype(np.float64) + 1.0) * 127.5) + .astype(np.uint8) + .tobytes() + ) + elif sample_width == 2: + # Keep the established float32-to-PCM16 quantization unchanged. + audio_bytes = (clipped_buffer * 32767).astype("> 8) + 128).astype(np.uint8).tobytes() + else: + pcm_buffer = buffer.astype(np.int32) << (8 * (sample_width - 2)) + if sample_width == 2: + audio_bytes = pcm_buffer.astype("