Base64 in AI audio: speech recognition, TTS, and streaming
Learn where Base64 fits in AI voice workflows, how to decode audio responses, and why PCM, WAV, codecs, sample rates, and stream boundaries matter.
Where Base64 fits in a voice pipeline
A speech application captures audio, sends it to a model, and receives text or generated audio. Base64 is one way to carry the audio bytes through text-based messages. It does not recognize speech, synthesize a voice, improve audio quality, or hide a recording.
Microphone or file
→ audio bytes in the required codec/container
→ Base64 only if the transport field requires text
→ speech recognition or an audio model
→ transcript or generated audio bytes
→ decode if necessary, then play in the correct format
For example, Google Cloud Speech-to-Text documents Base64 for inline audio in REST JSON, while its client-library and gRPC paths accept binary audio. Sending an already encoded string to a bytes parameter can encode it twice. See the audio encoding guide.
Speech recognition and text-to-speech have different payloads
| Workflow | Input | Output to inspect |
|---|---|---|
| Speech recognition | Audio file, bytes, or a supported file reference | Transcript and recognition metadata |
| Text-to-speech (TTS) | Text plus voice/audio settings | Audio bytes, sometimes represented as Base64 in JSON |
| Realtime voice | Ordered audio chunks and session events | Audio chunks, text, and control events |
Google Cloud TTS’s REST text.synthesize response uses a Base64 audioContent field. Its LINEAR16 result includes a WAV header. A client SDK may expose this field as bytes already; inspect its documented type before decoding. See the TTS response reference.
Do not generalize one service’s field names or output format to another. Some endpoints return a binary HTTP response, use multipart uploads, or accept file IDs. Follow the selected endpoint’s transport contract and current size limits.
PCM is not a WAV file
PCM describes audio samples; WAV is a container that can describe sample format and timing. A raw PCM buffer needs external information such as sample rate, channel count, bit depth, and byte order. MP3 and Opus encode samples differently. Base64 preserves whichever bytes you feed it.
If 24 kHz audio is played as 16 kHz, playback speed and pitch change. Setting a label does not resample audio. Renaming a PCM buffer to recording.wav does not add a WAV header. Concatenating complete WAV files does not produce a valid single recording.
The Gemini Live audio guide describes raw PCM audio and required rates for its streaming interface. Check the current model and endpoint contract before preparing samples; the local example below is a demonstration, not a universal provider configuration.
Python: make a WAV, encode it, and verify the decoded audio
This standalone example generates one second of synthetic silence as 16 kHz mono, signed 16-bit little-endian PCM. It wraps the samples in WAV, simulates a JSON Base64 field, then decodes and checks both the bytes and audio metadata. It records nothing, uploads nothing, and writes no files.
import base64
import io
import json
import wave
sample_rate = 16000
channels = 1
sample_width = 2 # 16-bit PCM: two bytes per sample
pcm = b"\x00\x00" * sample_rate # one second of silence
buffer = io.BytesIO()
with wave.open(buffer, "wb") as wav:
wav.setnchannels(channels)
wav.setsampwidth(sample_width)
wav.setframerate(sample_rate)
wav.writeframes(pcm)
original_wav = buffer.getvalue()
# Local demonstration, not a complete provider request.
message = json.dumps({
"audioContent": base64.b64encode(original_wav).decode("ascii")
})
value = json.loads(message)["audioContent"]
limit = 1024 * 1024 # example decoded-size limit
if len(value) > 4 * ((limit + 2) // 3):
raise ValueError("Encoded audio is too large")
restored = base64.b64decode(value, validate=True)
if len(restored) > limit:
raise ValueError("Decoded audio is too large")
assert restored == original_wav
with wave.open(io.BytesIO(restored), "rb") as wav:
assert wav.getnchannels() == channels
assert wav.getsampwidth() == sample_width
assert wav.getframerate() == sample_rate
assert wav.getnframes() == sample_rate
assert wav.readframes(sample_rate) == pcm
print(f"Verified {len(restored)} WAV bytes and 1 second of audio")
For real raw PCM, only add a WAV container after confirming the actual sample format. This example does not resample or transcode compressed audio. The Python wave documentation describes the supported WAV operations.
Streaming: decode each event at the right boundary
Some protocols encode each audio event independently; others split a continuous encoded stream. These require different handling. For independently encoded events, decode each complete field and assemble the decoded bytes in order. Joining padded Base64 strings before decoding can fail or lose later chunks.
import base64
# Two independently encoded events carrying the same raw PCM format.
# Their sizes intentionally produce Base64 padding.
chunks = [b"\x01\x00", b"\x02\x00\x03\x00"]
events = [base64.b64encode(chunk).decode("ascii") for chunk in chunks]
recovered = b"".join(base64.b64decode(event, validate=True) for event in events)
assert recovered == b"\x01\x00\x02\x00\x03\x00"
print("Independent audio events decoded in order")
This demonstration joins raw PCM chunks with the same format, not complete WAV files or arbitrary compressed fragments. In a real session, handle ordering, backpressure, cancellation, interruptions, and end-of-turn signals. Bound each event and the accumulated buffer. If the protocol fragments a continuous Base64 value, buffer incomplete four-character groups instead.
For scale, 16 kHz mono 16-bit PCM uses 32,000 bytes per second. One minute is 1,920,000 raw bytes or 2,560,000 Base64 characters before event metadata. Base64 does not reduce bandwidth or model latency. A protocol supporting binary frames or a media transport can avoid this text expansion.
Debug locally and protect recordings
- Verify the input type: raw Base64, Data URL, file bytes, or file reference.
- Decode and check the actual codec/container; do not rely on the extension.
- Confirm rate, channels, sample format, and whether output is a complete file or a chunk.
- Compare recovered bytes and duration using a small synthetic fixture first.
- Enforce encoded and decoded size limits, then check the provider’s own request limits.
Use Audio ↔ Base64 to inspect supported WAV, MP3, FLAC, Ogg Vorbis/Opus, and M4A files locally. The tool limits raw files to 10 MiB and encoded input to 14 MiB. It does not accept raw PCM or WebM, perform transcription, or call an AI service. Those limits belong to this tool, not a provider.
A Base64 recording remains the original recording in reversible form. Avoid storing payloads in logs, analytics events, error trackers, or shared prompts. Local conversion does not change what happens if you later upload the result to a speech service. Use appropriate access and retention settings for that separate step.
For reusable decoding helpers, read Python Base64 examples. For AI-assisted implementation, see Base64 decoding and encoding with AI.