Skip to content

Commit 40ac067

Browse files
committed
Convert g711 from twilio to pcm16
1 parent f932c7c commit 40ac067

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

llmstack/server/consumers.py

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import asyncio
2+
import audioop
23
import base64
34
import importlib
45
import json
@@ -518,7 +519,7 @@ async def connect(self):
518519
self._source,
519520
self.scope.get("user", None),
520521
app_data_config_override={
521-
"input_audio_format": "g711_ulaw",
522+
"input_audio_format": "pcm16",
522523
"output_audio_format": "g711_ulaw",
523524
},
524525
)
@@ -580,11 +581,24 @@ async def _respond_to_event(self, text_data):
580581
self._app_runner = None
581582
elif event == "media":
582583
encoded_audio_chunk = json_data.get("media", {}).get("payload", "")
583-
if not encoded_audio_chunk:
584+
if not encoded_audio_chunk or not self._input_audio_stream:
584585
return
585586

586-
if self._input_audio_stream:
587-
self._input_audio_stream.append_chunk(base64.b64decode(encoded_audio_chunk))
587+
try:
588+
# Decode base64 to get g711 ulaw data
589+
ulaw_data = base64.b64decode(encoded_audio_chunk)
590+
591+
# Convert ulaw to PCM16 (lin)
592+
pcm_data = audioop.ulaw2lin(ulaw_data, 2) # 2 bytes per sample for 16-bit
593+
594+
# Upsample from 8kHz to 24kHz
595+
pcm_upsampled = audioop.ratecv(pcm_data, 2, 1, 8000, 24000, None)[0]
596+
597+
# Append the converted and upsampled data
598+
self._input_audio_stream.append_chunk(pcm_upsampled)
599+
600+
except Exception as e:
601+
logger.exception(f"Error converting audio format: {e}")
588602

589603
elif event == "mark":
590604
logger.info(f"Received mark event from twilio: {json_data}")

0 commit comments

Comments
 (0)