|
20 | 20 | The text to speak, in the profile's language. |
21 | 21 | ``response_format`` |
22 | 22 | ``wav`` (default), ``mp3``, ``flac``, ``opus``, ``pcm`` (raw 16-bit |
23 | | - little-endian mono at the engine's sample rate), ``aac`` (needs ffmpeg). |
| 23 | + little-endian mono at 24 kHz, as OpenAI defines it), ``aac`` (needs ffmpeg). |
24 | 24 | ``speed`` |
25 | 25 | 0.25-4.0, applied as a pitch-preserving time stretch after synthesis. |
26 | 26 | ``instructions`` |
|
66 | 66 | "aac": (["-c:a", "aac", "-b:a", "128k", "-f", "adts"], "audio/aac"), |
67 | 67 | } |
68 | 68 | RESPONSE_FORMATS = (*_SOUNDFILE_FORMATS, "pcm", *_FFMPEG_FORMATS) |
| 69 | +PCM_SAMPLE_RATE = 24000 |
69 | 70 |
|
70 | 71 | # Voicebox launched long after the OpenAI `created` epoch convention; a fixed |
71 | 72 | # value keeps the field deterministic for clients that display it. |
@@ -115,7 +116,9 @@ class SpeechRequest(BaseModel): |
115 | 116 |
|
116 | 117 |
|
117 | 118 | def _available_formats() -> list[str]: |
118 | | - formats = [f for f in RESPONSE_FORMATS if f not in _FFMPEG_FORMATS] |
| 119 | + """Formats this server can actually produce, given its libsndfile build and PATH.""" |
| 120 | + formats = ["pcm"] |
| 121 | + formats.extend(f for f, (fmt, _, _) in _SOUNDFILE_FORMATS.items() if fmt in sf.available_formats()) |
119 | 122 | if shutil.which("ffmpeg"): |
120 | 123 | formats.extend(_FFMPEG_FORMATS) |
121 | 124 | return formats |
@@ -195,6 +198,12 @@ def encode_audio(audio: np.ndarray, sample_rate: int, response_format: str) -> t |
195 | 198 | import io |
196 | 199 |
|
197 | 200 | if response_format == "pcm": |
| 201 | + # OpenAI defines pcm as headerless 16-bit mono at 24 kHz; the body |
| 202 | + # carries no rate, so engines at another rate (LuxTTS: 48 kHz) must be resampled. |
| 203 | + if sample_rate != PCM_SAMPLE_RATE: |
| 204 | + import librosa |
| 205 | + |
| 206 | + audio = librosa.resample(audio.astype(np.float32), orig_sr=sample_rate, target_sr=PCM_SAMPLE_RATE) |
198 | 207 | pcm = np.clip(audio, -1.0, 1.0) |
199 | 208 | return (pcm * 32767).astype("<i2").tobytes(), "audio/pcm" |
200 | 209 |
|
@@ -300,10 +309,11 @@ async def _create_speech(request: Request, db: Session) -> Response: |
300 | 309 | param = ".".join(str(p) for p in first.get("loc", ())) or None |
301 | 310 | raise OpenAIError(400, f"Invalid value for '{param}': {first['msg']}", param=param) from exc |
302 | 311 |
|
303 | | - if data.response_format not in RESPONSE_FORMATS: |
| 312 | + if data.response_format not in _available_formats(): |
304 | 313 | raise OpenAIError( |
305 | 314 | 400, |
306 | | - f"Invalid response_format '{data.response_format}'. Supported: {', '.join(RESPONSE_FORMATS)}.", |
| 315 | + f"Invalid response_format '{data.response_format}'. Supported on this server: " |
| 316 | + f"{', '.join(_available_formats())}.", |
307 | 317 | param="response_format", |
308 | 318 | code="unsupported_format", |
309 | 319 | ) |
|
0 commit comments