Use realtime transcription when your application needs text from a microphone, call, or other live audio stream without a spoken assistant response. The recommended model returns transcript deltas as speech arrives and a final transcript when your application commits each audio turn.
For server-side WebSocket transcription with a standard API key, connect to wss://api.openai.com/v1/realtime?intent=transcription. Use the authentication header shown in the WebSocket guide, but omit model from the URL. That guide’s model-based URL creates a conversation session and doesn’t accept the transcription update below.
After the connection opens, send session.update with type: "transcription" and select gpt-live-transcribe in the session configuration. For browser audio, see WebRTC.
This example uses 24 kHz PCM audio. In gpt-live-transcribe transcription sessions, omit audio.input.turn_detection or set it to null. The model doesn’t support server_vad or semantic_vad. For the full session configuration, see the Realtime sessions reference.
Create a short-lived client secret in an authenticated request handler on your server. Keep OPENAI_API_KEY on the server. Wherever the example uses hashed-user-id, substitute a stable hash of the requesting user’s ID.
Set the Cache-Control: no-store header on the response. Send the JSON only to the authenticated user. Remove any code that prints or logs the secret. In the browser, use value from the JSON response as the bearer token when connecting over WebRTC.
A completion event contains the final transcript for the committed item:
123456{ "type": "conversation.item.input_audio_transcription.completed", "item_id": "item_003", "content_index": 0, "transcript": "Hello, how are you?"}
Ordering between completion events from different speech turns isn’t guaranteed. Use item_id to match transcription events to committed input items.
After configuring a transcription session, use this function to send mono PCM16 audio at 24 kHz, commit the turn, and match the final transcript to the committed item:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38using OpenAI.Realtime;#pragma warning disable OPENAI002RealtimeTranscriptionSessionInputAudioOptions input = new(){ AudioFormat = new RealtimePcmAudioFormat(), AudioTranscriptionOptions = new() { Model = "gpt-live-transcribe" }};input.DisableTurnDetection();await session.SendCommandAsync(new RealtimeClientCommandSessionUpdate(new RealtimeTranscriptionSessionOptions{ AudioOptions = new() { InputAudioOptions = input }}), timeout.Token);byte[] audio = await File.ReadAllBytesAsync("speech.pcm", timeout.Token);for (int offset = 0; offset < audio.Length; offset += 9600){ BinaryData chunk = BinaryData.FromBytes(audio.AsMemory(offset, Math.Min(9600, audio.Length - offset))); await session.SendCommandAsync(new RealtimeClientCommandInputAudioBufferAppend(chunk), timeout.Token);}await session.SendCommandAsync(new RealtimeClientCommandInputAudioBufferCommit(), timeout.Token);string? itemId = null;await foreach (RealtimeServerUpdate update in session.ReceiveUpdatesAsync(timeout.Token)){ if (update is RealtimeServerUpdateError error) throw new InvalidOperationException(error.Error.Message); if (update is RealtimeServerUpdateInputAudioBufferCommitted committed) itemId = committed.ItemId; if (update is RealtimeServerUpdateConversationItemInputAudioTranscriptionDelta delta) Console.Error.WriteLine($"Partial transcript ({delta.ItemId}): {delta.Delta}"); if (update is RealtimeServerUpdateConversationItemInputAudioTranscriptionFailed failed && failed.ItemId == itemId) throw new InvalidOperationException(failed.Error.Message); if (update is RealtimeServerUpdateConversationItemInputAudioTranscriptionCompleted transcript && transcript.ItemId == itemId) { Console.WriteLine($"Final transcript: {transcript.Transcript}"); return; }}throw new InvalidOperationException("Session ended before the committed audio was transcribed.");
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65require "openai"require "base64"client = OpenAI::Client.newclient.realtime.connect_transcription do |connection| connection.session.update( type: :transcription, audio: { input: { format: { type: "audio/pcm", rate: 24000 }, transcription: { model: "gpt-live-transcribe" }, turn_detection: nil } } ) updated = connection.find do |event| raise event.error.message if event.is_a?(OpenAI::Realtime::RealtimeErrorEvent) event.is_a?(OpenAI::Realtime::SessionUpdatedEvent) end raise "Connection closed before transcription configuration" unless updated # speech.pcm contains mono PCM16 audio sampled at 24 kHz. raise "Expected nonempty PCM16 audio" unless File.size("speech.pcm").positive? && File.size("speech.pcm").even? File.open("speech.pcm", "rb") do |input| while (chunk = input.read(9600)) connection.input_audio_buffer.append(audio: Base64.strict_encode64(chunk)) end end connection.input_audio_buffer.commit state = {} pending_deltas = [] completed = connection.find do |event| case event when OpenAI::Realtime::InputAudioBufferCommittedEvent state[:item_id] = event.item_id pending_deltas.each do |delta| warn "Partial transcript (#{delta.item_id}): #{delta.delta}" if delta.item_id == state[:item_id] end pending_deltas.clear when OpenAI::Realtime::ConversationItemInputAudioTranscriptionDeltaEvent if state[:item_id].nil? pending_deltas << event elsif event.item_id == state[:item_id] warn "Partial transcript (#{event.item_id}): #{event.delta}" end when OpenAI::Realtime::ConversationItemInputAudioTranscriptionCompletedEvent if state[:item_id] && event.item_id == state[:item_id] puts "Final transcript: #{event.transcript}" next true end when OpenAI::Realtime::ConversationItemInputAudioTranscriptionFailedEvent raise "Transcription failed" if state[:item_id] && event.item_id == state[:item_id] when OpenAI::Realtime::RealtimeErrorEvent raise event.error.message end false end raise "Connection closed before the committed item's final transcript" unless completedend
Add transcription context
Add context when the audio contains specialized vocabulary or more than one expected language. Send another session.update event to change the transcription configuration during an existing session.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22{"type": "session.update","session": {"type": "transcription","audio": {"input": {"format": {"type": "audio/pcm","rate": 24000 },"transcription": {"model": "gpt-live-transcribe","prompt": "A customer support call about a premium plan and account AC-42.","keywords": ["premium plan", "AC-42", "billing"],"languages": ["en", "fr"],"delay": "low" },"turn_detection": null } } }}
Use prompt to describe the recording or its setting.
Use keywords for product names, acronyms, and other literal terms that may appear in the audio.
Use languages for expected input languages.
Supported language-code formats include:
ISO 639-1 codes, such as en, es, and fr.
Selected ISO 639-3 codes, such as eng, spa, yue, and cmn.
Regional zh locale codes, such as zh-cn, zh-tw, and zh-hk.
The Realtime API rejects unsupported or incorrectly formatted language codes.
Keywords are hints, not required output. Keep each keyword on one line and don’t include <, >, a carriage return, or a line feed. The Realtime API rejects the session update if a keyword contains one of these characters or prompt exceeds the model’s length limit.
gpt-live-transcribe uses languages instead of the singular language field. Don’t send both.
Transcribe a committed turn
Use gpt-transcribe in a Realtime session only when you specifically need transcription to begin after a committed audio turn or need detected-language output. This specialized workflow requires a WebSocket connection.
When gpt-transcribe performs input transcription in a Realtime API session or runs in a dedicated transcription session, it automatically uses earlier transcribed turns as context.
Append audio and send input_audio_buffer.commit. The model can then emit transcript deltas before the final completion event. Its completion event also includes detected languages:
When gpt-transcribe can’t make a reliable language prediction, languages is an empty array. gpt-live-transcribe doesn’t return detected-language predictions.
Record mono PCM16 audio at 24 kHz. Keep the WebSocket open after stopping the microphone so you can commit the turn and receive the final transcript.
For functions that take transcriptionModel, pass "gpt-transcribe". Use Linux with FFmpeg and a default ALSA microphone. For C#, also install setsid from util-linux. Press Ctrl+Â CÂ to stop recording and commit the turn.
For TypeScript, Go, and Ruby, pass an open transcription connection to the recording function. Use FFmpeg with ALSA for TypeScript or PortAudio for Go and Ruby. After recording, send input_audio_buffer.commit.
For Python, import asyncio, base64, json, logging, websockets, and sounddevice as sd. Set SAMPLE_RATE = 24000 and CHUNK_SIZE = 2400. Run the loop in an async function with the configured WebSocket as ws. Break out of the loop at the end of the turn and send input_audio_buffer.commit.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280using System;using System.ClientModel.Primitives;using System.Collections.Generic;using System.Diagnostics;using System.IO;using System.Net.WebSockets;using System.Text;using System.Text.Json;using System.Threading;using System.Threading.Tasks;using OpenAI.Realtime;#pragma warning disable OPENAI002namespace OpenAI.Docs.Examples.RealtimeMicrophone;internal static class RealtimeTranscriptionMicrophone{ // Linux prerequisite: FFmpeg with ALSA input and an accessible default microphone. // Ctrl+C stops recording; the connection stays open for the final transcript. public static async Task TranscribeAsync(string transcriptionModel) { string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new InvalidOperationException("Set OPENAI_API_KEY."); RealtimeClient client = new(key); await TranscribeAsync(client, transcriptionModel); } private static async Task TranscribeAsync(RealtimeClient client, string transcriptionModel) { using CancellationTokenSource lifetime = new(); using CancellationTokenSource captureStop = new(); using CancellationTokenSource captureAbort = new(); ConsoleCancelEventHandler stop = (_, e) => { e.Cancel = true; captureStop.Cancel(); }; Console.CancelKeyPress += stop; try { using CancellationTokenSource setup = new(TimeSpan.FromSeconds(30)); using RealtimeSessionClient session = await client.StartTranscriptionSessionAsync( cancellationToken: setup.Token); lifetime.CancelAfter(TimeSpan.FromSeconds(30)); await using IAsyncEnumerator<RealtimeServerUpdate> updates = session .ReceiveUpdatesAsync(lifetime.Token).GetAsyncEnumerator(); RealtimeServerUpdateSessionCreated created = await WaitForAsync<RealtimeServerUpdateSessionCreated>(updates); if (created.Session is not RealtimeTranscriptionSession transcription || string.IsNullOrWhiteSpace(transcription.Id)) throw new InvalidOperationException("Expected a transcription session."); RealtimeTranscriptionSessionInputAudioOptions input = new() { AudioFormat = new RealtimePcmAudioFormat(), // 24 kHz, signed PCM16, little-endian AudioTranscriptionOptions = new() { Model = transcriptionModel, Language = "en" } }; input.DisableTurnDetection(); await session.ConfigureTranscriptionSessionAsync(new() { AudioOptions = new() { InputAudioOptions = input } }, setup.Token); RealtimeServerUpdateSessionUpdated configured = await WaitForAsync<RealtimeServerUpdateSessionUpdated>(updates); CheckSettings(configured.Session, input.AudioTranscriptionOptions.Model); lifetime.CancelAfter(Timeout.InfiniteTimeSpan); Task<string> receipt = ReceiveTranscriptAsync(updates); Task capture = RecordMicrophoneAsync(session, captureStop.Token, captureAbort.Token); try { Task first = await Task.WhenAny(capture, receipt); if (first == receipt) { // Surface a socket/API error immediately, even during continuous capture. await receipt; throw new InvalidOperationException("Transcript arrived before manual commit."); } await capture; using CancellationTokenSource finish = new(TimeSpan.FromSeconds(60)); await session.CommitPendingAudioAsync(finish.Token); lifetime.CancelAfter(TimeSpan.FromSeconds(60)); Console.WriteLine(await receipt); } finally { captureStop.Cancel(); captureAbort.Cancel(); try { try { await capture; } catch (OperationCanceledException) when (captureAbort.IsCancellationRequested) { } } finally { try { if (session.WebSocket.State is WebSocketState.Open or WebSocketState.CloseReceived) { using CancellationTokenSource close = new(TimeSpan.FromSeconds(5)); await session.WebSocket.CloseOutputAsync( WebSocketCloseStatus.NormalClosure, "Transcription finished", close.Token); } } finally { lifetime.Cancel(); try { await receipt; } catch (OperationCanceledException) when (lifetime.IsCancellationRequested) { } } } } } finally { lifetime.Cancel(); Console.CancelKeyPress -= stop; } } // Linux prerequisites: FFmpeg, ALSA input, and setsid from util-linux. // Keep FFmpeg outside the terminal signal group; Ctrl+C stops capture in .NET. // Cancel stop to finish the current frame before committing the captured audio. private static async Task RecordMicrophoneAsync( RealtimeSessionClient session, CancellationToken stop, CancellationToken lifetime) { ProcessStartInfo start = new("setsid") { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true }; start.ArgumentList.Add("ffmpeg"); foreach (string argument in new[] { "-nostdin", "-hide_banner", "-loglevel", "warning", "-f", "alsa", "-i", "default", "-ac", "1", "-ar", "24000", "-acodec", "pcm_s16le", "-f", "s16le", "pipe:1" }) start.ArgumentList.Add(argument); using Process recorder = Process.Start(start) ?? throw new InvalidOperationException("Could not start FFmpeg."); Task<string> diagnostics = ReadDiagnosticsAsync(recorder.StandardError); long frames = 0; string diagnostic; try { byte[] pcm = new byte[4800]; // Exactly 100 ms at 24 kHz, one channel, two bytes/sample. while (!stop.IsCancellationRequested) { // Finish the current frame after Ctrl+C; a stalled device fails within five seconds. using CancellationTokenSource read = CancellationTokenSource.CreateLinkedTokenSource(lifetime); read.CancelAfter(TimeSpan.FromSeconds(5)); await recorder.StandardOutput.BaseStream.ReadExactlyAsync(pcm, read.Token); using CancellationTokenSource send = CancellationTokenSource.CreateLinkedTokenSource(lifetime); send.CancelAfter(TimeSpan.FromSeconds(30)); await session.SendInputAudioAsync(BinaryData.FromBytes(pcm), send.Token); frames++; } if (frames == 0) throw new InvalidOperationException("No microphone audio was captured."); if (recorder.HasExited) throw new InvalidOperationException("FFmpeg exited before capture stopped."); } finally { if (!recorder.HasExited) recorder.Kill(entireProcessTree: true); await recorder.WaitForExitAsync(); diagnostic = await diagnostics; } // FFmpeg can infer the input layout. Reject other warnings and truncated logs. if (diagnostic.Length == MaxDiagnosticCharacters || Array.Exists( diagnostic.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries), line => !IsChannelLayoutHint(line))) throw new InvalidOperationException($"FFmpeg capture diagnostics: {diagnostic}"); } private const int MaxDiagnosticCharacters = 4096; private static bool IsChannelLayoutHint(string line) => line is "Guessed Channel Layout for Input Stream #0.0 : mono" or "Guessed Channel Layout for Input Stream #0.0 : stereo" || (line.StartsWith("[aist#0:0/", StringComparison.Ordinal) && line.IndexOf(']') == line.LastIndexOf(']') && (line.EndsWith("] Guessed Channel Layout: mono", StringComparison.Ordinal) || line.EndsWith("] Guessed Channel Layout: stereo", StringComparison.Ordinal))); private static async Task<string> ReadDiagnosticsAsync(StreamReader reader) { StringBuilder tail = new(); char[] buffer = new char[1024]; int count; while ((count = await reader.ReadAsync(buffer.AsMemory())) != 0) { tail.Append(buffer, 0, count); if (tail.Length > MaxDiagnosticCharacters) tail.Remove(0, tail.Length - MaxDiagnosticCharacters); } return tail.ToString(); } private static async Task<T> WaitForAsync<T>( IAsyncEnumerator<RealtimeServerUpdate> updates) where T : RealtimeServerUpdate { while (await updates.MoveNextAsync()) { if (updates.Current is RealtimeServerUpdateError error) throw new InvalidOperationException(error.Error.Message); if (updates.Current is T expected) return expected; } throw new InvalidOperationException($"Socket closed before {typeof(T).Name}."); } private static void CheckSettings(RealtimeSession session, string model) { if (session is not RealtimeTranscriptionSession transcriptionSession || transcriptionSession.AudioOptions?.InputAudioOptions is not { } audioInput) throw new InvalidOperationException("Expected transcription audio settings."); // SDK serialization omits a null TurnDetection property. Preserve the // server's explicit null acknowledgment through its retained JSON patch.#pragma warning disable SCME0001 if (!audioInput.Patch.TryGetJson("$.turn_detection"u8, out ReadOnlyMemory<byte> rawDetection)) throw new InvalidOperationException("Server omitted the turn-detection acknowledgment.");#pragma warning restore SCME0001 using JsonDocument detection = JsonDocument.Parse(rawDetection); using JsonDocument document = JsonDocument.Parse(ModelReaderWriter.Write(session)); JsonElement root = document.RootElement; JsonElement input = root.GetProperty("audio").GetProperty("input"); JsonElement format = input.GetProperty("format"); JsonElement transcription = input.GetProperty("transcription"); bool language = transcription.TryGetProperty("language", out JsonElement hint) && hint.GetString() == "en"; if (transcription.TryGetProperty("languages", out JsonElement languages)) { bool canonical = languages.ValueKind == JsonValueKind.Array && languages.GetArrayLength() == 1 && languages[0].GetString() == "en"; language = canonical && (!transcription.TryGetProperty("language", out hint) || hint.GetString() == "en"); } if (root.GetProperty("type").GetString() != "transcription" || format.GetProperty("type").GetString() != "audio/pcm" || format.GetProperty("rate").GetInt32() != 24000 || transcription.GetProperty("model").GetString() != model || !language || detection.RootElement.ValueKind != JsonValueKind.Null) throw new InvalidOperationException("Server did not acknowledge the requested audio settings."); } private static async Task<string> ReceiveTranscriptAsync( IAsyncEnumerator<RealtimeServerUpdate> updates) { string? itemId = null; while (await updates.MoveNextAsync()) { switch (updates.Current) { case RealtimeServerUpdateError error: throw new InvalidOperationException(error.Error.Message); case RealtimeServerUpdateInputAudioBufferCommitted committed: if (itemId is not null || string.IsNullOrWhiteSpace(committed.ItemId)) throw new InvalidOperationException("Invalid or duplicate commit acknowledgment."); itemId = committed.ItemId; break; case RealtimeServerUpdateConversationItemInputAudioTranscriptionFailed failed: throw new InvalidOperationException($"Transcription failed for {failed.ItemId}: {failed.Error.Message}"); case RealtimeServerUpdateConversationItemInputAudioTranscriptionCompleted completed: if (itemId is null || completed.ItemId != itemId || completed.ContentIndex != 0) throw new InvalidOperationException("Transcript did not match the committed audio."); return completed.Transcript; } } throw new InvalidOperationException("Socket closed before transcription completed."); }}#pragma warning restore OPENAI002
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41require "openai"require "base64"require "ffi-portaudio"def check_audio(result) raise FFI::PortAudio::API.Pa_GetErrorText(result) unless result == :paNoErrorenddef record_microphone(connection) state = {} previous_handler = Signal.trap("INT") { state[:stopped] = true } begin audio = FFI::PortAudio::API check_audio(audio.Pa_Initialize) begin pointer = FFI::MemoryPointer.new(:pointer) check_audio(audio.Pa_OpenDefaultStream(pointer, 1, 0, FFI::PortAudio::API::Int16, 24_000.0, 2400, nil, nil)) stream = pointer.read_pointer begin check_audio(audio.Pa_StartStream(stream)) begin buffer = FFI::MemoryPointer.new(:int16, 2400) until state[:stopped] # Read 100 ms of real mono PCM16 input, preserving the exact bytes. # PortAudio reports an error if input frames overflow or are lost. check_audio(audio.Pa_ReadStream(stream, buffer, 2400)) connection.input_audio_buffer.append(audio: Base64.strict_encode64(buffer.get_bytes(0, 4800))) end ensure check_audio(audio.Pa_StopStream(stream)) end ensure check_audio(audio.Pa_CloseStream(stream)) end ensure check_audio(audio.Pa_Terminate) end ensure Signal.trap("INT", previous_handler) endend
Tune latency and accuracy
Streaming transcription trades latency for transcript quality. Lower delay settings can produce earlier partial text. Higher delay settings give the model more audio context before emitting text and can improve word error rate.
Start by setting audio.input.transcription.delay and testing against your real audio. Useful starting points are:
minimal for the most latency-sensitive interactions;
low for low-latency live captions;
medium for a balanced latency/accuracy tradeoff;
high when accuracy matters more than immediate display;
xhigh when your workflow can tolerate the most delay for more context.
The exact delay in milliseconds can vary by model configuration, so benchmark with representative audio instead of assuming a fixed timing per level.
Don’t choose a setting from synthetic audio alone. Test with representative microphones, telephony audio, accents, background noise, code-switching, domain vocabulary, and long sessions.
Handle confidence, timestamps, and speaker labels
gpt-live-transcribe doesn’t return word-level timestamps, speaker labels, or transcription confidence scores. If your application requires timestamps or speaker labels, use a compatible file transcription model or add an application-level fallback.
Production checklist
Pick a target latency and accuracy threshold before tuning.
Test against real production audio, not only clean samples.
Test each target language.
Include numbers, dates, currency, email addresses, product names, and domain terms in your eval set.
Track empty, truncated, and delayed transcripts apart from word error rate.
Decide how your UI should revise partial text when later deltas correct earlier text.
Use item_id to order and reconcile final transcripts.
Keep a fallback path for unsupported timestamps, speaker labels, or confidence fields.