实时转写会话的建立与延迟调优

面向需要从麦克风或通话等实时音频流获取文字、但不要求语音助手应答的应用,介绍通过 WebSocket 建立转写会话、流式发送音频并处理增量转写事件的方法,同时说明延迟与准确率的取舍以及模型能力边界。

# 实时转录 > 完整的文件索引见 [页:1](<https://developers.openai.com/llms.txt>)。可附加文档页的下图版 `.md` 转到页面 URL。 当您的应用程序需要从麦克风、呼叫或其他没有语音助理响应的实时音频流中获取文本时,请使用实时记录。推荐的模型在语音到达时返回 Dertas 记录,并在您每次输入音频时返回最后记录。 开始 [`gpt-live-transcribe`](https://developers.openai.com/api/docs/models/gpt-live-transcribe)使用时 [存档转录](https://developers.openai.com/api/docs/guides/speech-to-text) 如果您的音频已被录制, 或者看到 [译名概览](https://developers.openai.com/api/docs/guides/transcription) 比较工作流程。 ## 创建复制会话 对于服务器侧的 WebSocket 转录带标准 API 键,连接到 `wss://api.openai.com/v1/realtime?intent=transcription`中显示的认证头。 [WebSocket 指南](https://developers.openai.com/api/docs/guides/voice-websockets?api=realtime),但省略 `model` 从URL. 该指南基于模型的URL创建了对话会话,不接受下面的抄录更新. 连接打开后发送 `session.update` 与 `type: "transcription"` 选择 `gpt-live-transcribe` 在会话配置中。关于浏览器音频,参见 [WebRTC](https://developers.openai.com/api/docs/guides/voice-webrtc?api=realtime). ```json { "type": "session.update", "session": { "type": "transcription", "audio": { "input": { "format": { "type": "audio/pcm", "rate": 24000 }, "transcription": { "model": "gpt-live-transcribe" }, "turn_detection": null } } } } ``` 此示例使用 24 kHz PCM 音频。 in `gpt-live-transcribe` 转录会话, 省略 `audio.input.turn_detection` 或设定为 `null`。该模型不支持 `server_vad` 或 时 间 `semantic_vad`。完整的会话配置,见 [实时会议参考](https://developers.openai.com/api/reference/resources/realtime/subresources/client_secrets). ### 创建浏览器复制的客户端秘密 在服务器上的认证请求处理器中创建短命客户端秘密。 保留 `OPENAI_API_KEY` 在服务器上。在示例使用的地方 `hashed-user-id`,替换请求用户的 ID 的稳定散列。 ```typescript const r = await fetch("https://api.openai.com/v1/realtime/client_secrets", { method: "POST", headers: { Authorization: `Bearer ${process.env.OPENAI_API_KEY}`, "Content-Type": "application/json", "OpenAI-Safety-Identifier": "hashed-user-id", }, body: JSON.stringify({ session: { type: "transcription", audio: { input: { transcription: { model: "gpt-live-transcribe" } } }, }, }), }); const data = await r.json(); ``` ```python import json import time from openai import OpenAI def validate_credential(payload: dict) -> None: session = payload.get("session", {}) model = ( session.get("audio", {}).get("input", {}).get("transcription", {}).get("model") ) if ( not isinstance(payload.get("value"), str) or not payload["value"].strip() or not isinstance(payload.get("expires_at"), int) or payload["expires_at"] <= time.time() or session.get("type") != "transcription" or model != "gpt-live-transcribe" ): raise ValueError("Invalid transcription client credential") def main() -> None: # Keep OPENAI_API_KEY on the server. Deliver this output only to the # authenticated requesting client; never record it in application logs. with OpenAI(timeout=30.0, max_retries=0) as client: secret = client.realtime.client_secrets.create( session={ "type": "transcription", "audio": {"input": {"transcription": {"model": "gpt-live-transcribe"}}}, }, extra_headers={"OpenAI-Safety-Identifier": "hashed-user-id"}, ) payload = secret.model_dump(mode="json", exclude_unset=True) validate_credential(payload) print(json.dumps(payload)) if __name__ == "__main__": main() ``` ```go ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() client := openai.NewClient() secret, err := client.Realtime.ClientSecrets.New(ctx, realtime.ClientSecretNewParams{ Session: realtime.ClientSecretNewParamsSessionUnion{ OfTranscription: &realtime.RealtimeTranscriptionSessionCreateRequestParam{ Audio: realtime.RealtimeTranscriptionSessionAudioParam{ Input: realtime.RealtimeTranscriptionSessionAudioInputParam{ Transcription: realtime.AudioTranscriptionParam{ Model: "gpt-live-transcribe", }, }, }, }, }, }, option.WithHeader("OpenAI-Safety-Identifier", "hashed-user-id")) if err != nil { log.Fatal(err) } // Return this short-lived credential only to your authenticated browser client. var output bytes.Buffer if err := json.Compact(&output, []byte(secret.RawJSON())); err != nil { log.Fatal(err) } fmt.Println(output.String()) ``` ```java import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.core.ObjectMappers; import com.openai.models.realtime.*; import com.openai.models.realtime.clientsecrets.ClientSecretCreateParams; var client = OpenAIOkHttpClient.fromEnv(); try { var secret = client .realtime() .clientSecrets() .create( ClientSecretCreateParams.builder() .putAdditionalHeader("OpenAI-Safety-Identifier", "hashed-user-id") .session( RealtimeTranscriptionSessionCreateRequest.builder() .audio( RealtimeTranscriptionSessionAudio.builder() .input( RealtimeTranscriptionSessionAudioInput.builder() .transcription( AudioTranscription.builder() .model("gpt-live-transcribe") .build()) .build()) .build()) .build()) .build()); // Return this ephemeral credential only to the authenticated requesting client. System.out.println(ObjectMappers.jsonMapper().writeValueAsString(secret)); } finally { client.close(); } ``` ```csharp using System.ClientModel; using System.ClientModel.Primitives; using System.Security.Claims; using System.Security.Cryptography; using System.Text; using System.Text.Json; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using OpenAI.Realtime; #pragma warning disable OPENAI002 namespace OpenAI.Docs.Examples.RealtimeWebrtcTranscription; // In your existing authenticated ASP.NET Core application: // app.MapPost("/session", (Func<HttpContext, Task<IResult>>) // WebrtcSessionTokenTranscription.HandleAsync).RequireAuthorization(); internal static class WebrtcSessionTokenTranscription { // This local preview rejects anonymous callers; use your application's // authentication middleware when mapping HandleAsync in the real host. internal static async Task RunAsync() { WebApplicationBuilder builder = WebApplication.CreateBuilder(); builder.WebHost.UseUrls("http://127.0.0.1:3000"); await using WebApplication app = builder.Build(); app.MapPost("/session", (Func<HttpContext, Task<IResult>>)HandleAsync); await app.RunAsync(); } internal static async Task<IResult> HandleAsync(HttpContext context) { context.Response.Headers.CacheControl = "no-store"; if (context.User.Identity?.IsAuthenticated != true) { return Results.Unauthorized(); } Claim? subject = context.User.FindFirst(ClaimTypes.NameIdentifier) ?? context.User.FindFirst("sub"); if (subject is null || string.IsNullOrWhiteSpace(subject.Value)) { return Results.Unauthorized(); } string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new InvalidOperationException("Set OPENAI_API_KEY on the server."); using HttpClient http = new(); string safetyIdentifier = Convert.ToHexString(SHA256.HashData( Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new { issuer = subject.Issuer, subject = subject.Value, })))).ToLowerInvariant(); http.DefaultRequestHeaders.Add("OpenAI-Safety-Identifier", safetyIdentifier); RealtimeClient client = new(new ApiKeyCredential(key), new RealtimeClientOptions { Transport = new HttpClientPipelineTransport(http) }); using CancellationTokenSource timeout = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted); timeout.CancelAfter(TimeSpan.FromSeconds(30)); ClientResult<CreateClientSecretResult> result = await client.CreateRealtimeClientSecretAsync( new CreateClientSecretOptions { SessionOptions = new RealtimeTranscriptionSessionOptions { AudioOptions = new RealtimeTranscriptionSessionAudioOptions { InputAudioOptions = new RealtimeTranscriptionSessionInputAudioOptions { AudioTranscriptionOptions = new RealtimeAudioTranscriptionOptions { Model = "gpt-live-transcribe" } } } } }, timeout.Token); // Preserve the entire returned JSON, including fields added by the API. string json = result.GetRawResponse().Content.ToString(); ValidateCredential(json); return Results.Content(json, "application/json"); } private static void ValidateCredential(string json) { using JsonDocument document = JsonDocument.Parse(json); JsonElement root = document.RootElement; if (!root.TryGetProperty("value", out JsonElement value) || value.ValueKind != JsonValueKind.String || string.IsNullOrWhiteSpace(value.GetString()) || !root.TryGetProperty("expires_at", out JsonElement expiry) || !expiry.TryGetInt64(out long expiresAt) || expiresAt <= DateTimeOffset.UtcNow.ToUnixTimeSeconds() || !root.TryGetProperty("session", out JsonElement session) || !session.TryGetProperty("type", out JsonElement type) || type.GetString() != "transcription" || !session.TryGetProperty("audio", out JsonElement audio) || !audio.TryGetProperty("input", out JsonElement input) || !input.TryGetProperty("transcription", out JsonElement transcription) || !transcription.TryGetProperty("model", out JsonElement model) || model.GetString() != "gpt-live-transcribe") { throw new InvalidOperationException("Invalid transcription client credential."); } } } #pragma warning restore OPENAI002 ``` ```ruby require "net/http" require "json" uri = URI("https://api.openai.com/v1/realtime/client_secrets") request = Net::HTTP::Post.new(uri) request["Authorization"] = "Bearer #{ENV.fetch("OPENAI_API_KEY")}" request["Content-Type"] = "application/json" request["OpenAI-Safety-Identifier"] = "hashed-user-id" request.body = JSON.generate( session: { type: "transcription", audio: { input: { transcription: { model: "gpt-live-transcribe" } } } } ) response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, open_timeout: 10, read_timeout: 30) do |http| http.request(request) end response.value session = JSON.parse(response.body) # Return the ephemeral secret only to the authenticated client that requested it. puts(JSON.generate(session)) ``` 设定 `Cache-Control: no-store` 回复时的页眉。 仅将 JSON 发送给经认证的用户。 删除任何打印或登录该密钥的代码。 在浏览器中, 使用 `value` 从 JSON 回复中作为无记名符号,当 [在 WebRTC 上连接](https://developers.openai.com/api/docs/guides/voice-webrtc?api=realtime). ## 串流音频 发送音频块 `input_audio_buffer.append`: ```typescript ws.send( JSON.stringify({ type: "input_audio_buffer.append", audio: base64Pcm16, }) ); ``` 发送 `input_audio_buffer.commit` 在每次音频转折的结尾处收到最后记录: ```typescript ws.send( JSON.stringify({ type: "input_audio_buffer.commit", }) ); ``` 使用客户端的 VAD 来检测语音的结束, 然后发送 `input_audio_buffer.commit`. ## 处理记录活动 收听递增的三角洲记录和完成活动: ```typescript ws.on("message", (data) => { const event = JSON.parse(data); if (event.type === "conversation.item.input_audio_transcription.delta") { process.stdout.write(event.delta); } if (event.type === "conversation.item.input_audio_transcription.completed") { console.log("\nFinal transcript:", event.transcript); } }); ``` 三角洲事件包含新获得的文字记录: ```json { "type": "conversation.item.input_audio_transcription.delta", "item_id": "item_003", "content_index": 0, "delta": "Hello," } ``` 完成活动载有承诺项目的最后记录: ```json { "type": "conversation.item.input_audio_transcription.completed", "item_id": "item_003", "content_index": 0, "transcript": "Hello, how are you?" } ``` 无法保证不同语音回合的补全事件之间的顺序。 使用 `item_id` 将复制事件与承诺的输入项目相匹配。 在配置一个转录会话后,使用此功能在 PCM16 音频发送到 24 kHz, 将转录, 并将最后的转录与承诺项匹配 : ```typescript // Use a transcription session configured for 24 kHz mono PCM16 and manual commits. function transcribeTurn( connection: OpenAIRealtimeWS, audio: Buffer ): Promise<string> { if (!audio.length || audio.length % 2) throw new Error("Expected nonempty PCM16 audio"); return new Promise((resolve, reject) => { let itemID: string | undefined; const completed = new Map<string, string>(); const failed = new Set<string>(); const timer = setTimeout( () => finish(new Error("Transcription timed out")), 120000 ); function finish(error?: Error, transcript?: string) { clearTimeout(timer); connection.off("event", onEvent); connection.off("error", onError); connection.socket.off("close", onClose); if (error) reject(error); else resolve(transcript!); } const onError = (error: Error) => finish(error); const onClose = () => finish(new Error("Connection closed before transcription")); const onEvent = (event: RealtimeServerEvent) => { if ( event.type === "conversation.item.input_audio_transcription.delta" && event.item_id === itemID ) console.error(`Partial transcript (${event.item_id}): ${event.delta}`); if (event.type === "input_audio_buffer.committed") itemID = event.item_id; if ( event.type === "conversation.item.input_audio_transcription.completed" ) completed.set(event.item_id, event.transcript); if (event.type === "conversation.item.input_audio_transcription.failed") failed.add(event.item_id); if (itemID && failed.has(itemID)) finish(new Error("Transcription failed")); else if (itemID && completed.has(itemID)) finish(undefined, completed.get(itemID)); }; connection.on("event", onEvent); connection.on("error", onError); connection.socket.on("close", onClose); for (let start = 0; start < audio.length; start += 9600) { connection.send({ type: "input_audio_buffer.append", audio: audio.subarray(start, start + 9600).toString("base64"), }); } connection.send({ type: "input_audio_buffer.commit" }); }); } ``` ```python import asyncio import base64 import sys from pathlib import Path from openai import AsyncOpenAI from openai.resources.realtime.realtime import AsyncRealtimeConnection async def receive(connection: AsyncRealtimeConnection): event = await connection.recv() if event.type == "error": raise RuntimeError(f"Realtime error: {event.error}") return event async def wait_for(connection: AsyncRealtimeConnection, event_type: str): while True: event = await receive(connection) if event.type == event_type: return event async def transcribe_turn(connection: AsyncRealtimeConnection, audio: bytes) -> str: if not audio or len(audio) % 2: raise ValueError("Expected nonempty 24 kHz mono little-endian PCM16 audio") # One manual turn per fresh session. Buffer results until its commit identifies it. item_id = None completed = {} failed = {} partials = {} async with asyncio.timeout(120): for start in range(0, len(audio), 9600): await connection.input_audio_buffer.append( audio=base64.b64encode(audio[start : start + 9600]).decode("ascii") ) await connection.input_audio_buffer.commit() while True: event = await receive(connection) if ( event.type in ( "conversation.item.input_audio_transcription.delta", "conversation.item.input_audio_transcription.completed", "conversation.item.input_audio_transcription.failed", ) and event.content_index != 0 ): raise RuntimeError("Unexpected transcription content part") if event.type == "input_audio_buffer.committed": if item_id is not None or not event.item_id: raise RuntimeError("Unexpected audio commit acknowledgment") item_id = event.item_id for delta in partials.pop(item_id, []): print(f"Partial transcript ({item_id}): {delta}", file=sys.stderr) elif event.type == "conversation.item.input_audio_transcription.delta": if event.item_id == item_id: print( f"Partial transcript ({item_id}): {event.delta}", file=sys.stderr, ) else: partials.setdefault(event.item_id, []).append(event.delta) elif event.type == "conversation.item.input_audio_transcription.completed": completed[event.item_id] = event.transcript elif event.type == "conversation.item.input_audio_transcription.failed": failed[event.item_id] = event.error if item_id in failed: raise RuntimeError(f"Transcription failed: {failed[item_id]}") if item_id in completed: transcript = completed[item_id] if not isinstance(transcript, str) or not transcript.strip(): raise RuntimeError("Transcription completed without text") return transcript async def main() -> None: # Raw 24 kHz mono little-endian PCM16, without a WAV header. audio = Path("speech.pcm").read_bytes() async with AsyncOpenAI() as client: async with client.realtime.connect( extra_query={"intent": "transcription"} ) as connection: async with asyncio.timeout(120): await wait_for(connection, "session.created") await connection.session.update( session={ "type": "transcription", "audio": { "input": { "format": {"type": "audio/pcm", "rate": 24000}, "transcription": {"model": "gpt-live-transcribe"}, "turn_detection": None, } }, } ) await wait_for(connection, "session.updated") print("Final transcript:", await transcribe_turn(connection, audio)) if __name__ == "__main__": asyncio.run(main()) ``` ```go func transcribeTurn(ctx context.Context, conn *realtime.RealtimeConnection, audio []byte) error { for start := 0; start < len(audio); start += 9600 { end := min(start+9600, len(audio)) if err := conn.Send(ctx, realtime.RealtimeClientEventParamOfInputAudioBufferAppend(base64.StdEncoding.EncodeToString(audio[start:end]))); err != nil { return err } } if err := conn.Send(ctx, realtime.RealtimeClientEventUnionParam{ OfInputAudioBufferCommit: &realtime.InputAudioBufferCommitEventParam{}, }); err != nil { return err } // Match the final transcript to the committed item, not event arrival order. var itemID string for { event, err := conn.Recv(ctx) if err != nil { return err } switch event.Type { case "input_audio_buffer.committed": itemID = event.OfInputAudioBufferCommittedEvent.ItemID case "conversation.item.input_audio_transcription.delta": delta := event.OfConversationItemInputAudioTranscriptionDeltaEvent if itemID != "" && delta.ItemID == itemID { fmt.Fprintf(os.Stderr, "Partial transcript (%s): %s\n", delta.ItemID, delta.Delta) } case "conversation.item.input_audio_transcription.completed": completed := event.OfConversationItemInputAudioTranscriptionCompletedEvent if itemID == "" || completed.ItemID != itemID { continue } fmt.Println("Final transcript:", completed.Transcript) return nil case "conversation.item.input_audio_transcription.failed": if itemID != "" && event.OfConversationItemInputAudioTranscriptionFailedEvent.ItemID == itemID { return fmt.Errorf("transcription failed") } case "error": return fmt.Errorf("Realtime API error: %s", event.OfRealtimeErrorEvent.Error.Message) } } } ``` ```java import com.openai.client.okhttp.OkHttpClient; import com.openai.core.ClientOptions; import com.openai.helpers.RealtimeConnection; import com.openai.helpers.RealtimeWebSocketOptions; import com.openai.models.realtime.*; import java.nio.file.*; import java.util.Base64; var http = OkHttpClient.builder().build(); var options = ClientOptions.builder() .fromEnv() .httpClient(http) .putHeader("OpenAI-Safety-Identifier", "hashed-user-id") .build(); try (http; var connection = RealtimeConnection.connect( options, RealtimeWebSocketOptions.builder().transcription().build())) { send( connection, RealtimeClientEvent.ofSessionUpdate( SessionUpdateEvent.builder() .session( RealtimeTranscriptionSessionCreateRequest.builder() .audio( RealtimeTranscriptionSessionAudio.builder() .input( RealtimeTranscriptionSessionAudioInput.builder() .format( RealtimeAudioFormats.AudioPcm.builder() .type( RealtimeAudioFormats.AudioPcm.Type.AUDIO_PCM) .rate(RealtimeAudioFormats.AudioPcm.Rate._24000) .build()) .turnDetection(com.openai.core.JsonValue.from(null)) .transcription( AudioTranscription.builder() .model("gpt-live-transcribe") .build()) .build()) .build()) .build()) .build())); while (true) { var event = connection.receive(); if (event.error().isPresent()) throw new IllegalStateException(event.error().orElseThrow().toString()); if (event.sessionUpdated().isPresent()) break; } byte[] audio = Files.readAllBytes(Path.of("speech.pcm")); if (audio.length == 0 || audio.length % 2 != 0) throw new IllegalArgumentException("Expected mono PCM16 at 24 kHz"); for (int start = 0; start < audio.length; start += 9600) { var chunk = java.util.Arrays.copyOfRange(audio, start, Math.min(start + 9600, audio.length)); send( connection, RealtimeClientEvent.ofInputAudioBufferAppend( InputAudioBufferAppendEvent.builder() .audio(Base64.getEncoder().encodeToString(chunk)) .build())); } send( connection, RealtimeClientEvent.ofInputAudioBufferCommit( InputAudioBufferCommitEvent.builder().build())); String itemId = null; while (true) { var event = connection.receive(); if (event.error().isPresent()) throw new IllegalStateException(event.error().orElseThrow().toString()); if (event.inputAudioBufferCommitted().isPresent()) itemId = event.inputAudioBufferCommitted().orElseThrow().itemId(); if (event.conversationItemInputAudioTranscriptionDelta().isPresent()) { var delta = event.conversationItemInputAudioTranscriptionDelta().orElseThrow(); if (delta.itemId().equals(itemId)) System.err.println( "Partial transcript (" + delta.itemId() + "): " + delta.delta().orElse("")); } if (event.conversationItemInputAudioTranscriptionCompleted().isPresent()) { var completed = event.conversationItemInputAudioTranscriptionCompleted().orElseThrow(); if (completed.itemId().equals(itemId)) { System.out.println("Final transcript: " + completed.transcript()); break; } } if (event.conversationItemInputAudioTranscriptionFailed().isPresent() && event .conversationItemInputAudioTranscriptionFailed() .orElseThrow() .itemId() .equals(itemId)) throw new IllegalStateException("Transcription failed"); } } static void send(RealtimeConnection connection, RealtimeClientEvent event) throws Exception { long deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(10); while (true) { try { connection.send(event); return; } catch (com.openai.core.http.WebSocketWriteNotAttempted.Busy busy) { if (System.nanoTime() >= deadline) throw busy; Thread.sleep(10); } } } ``` ```csharp using OpenAI.Realtime; #pragma warning disable OPENAI002 RealtimeTranscriptionSessionInputAudioOptions 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."); ``` ```ruby require "openai" require "base64" client = OpenAI::Client.new client.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 = {} completed = connection.find do |event| case event when OpenAI::Realtime::InputAudioBufferCommittedEvent state[:item_id] = event.item_id when OpenAI::Realtime::ConversationItemInputAudioTranscriptionDeltaEvent warn "Partial transcript (#{event.item_id}): #{event.delta}" if state[:item_id] && event.item_id == state[:item_id] 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 completed end ``` ## 添加转写上下文 当音频包含专门的词汇或不止一种预期语言时添加上下文。发送另一种语言 `session.update` 在当前会话中更改转录配置的事件。 ```json { "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 } } } } ``` - 使用( U) `prompt` 以描述录音或录音背景。 - 使用( U) `keywords` 用于产品名称、缩略语和音频中可能出现的其他文字术语。 - 使用( U) `languages` 用于预期输入语言。 支持的语言代码格式包括: - ISO 639 - 1 代码,例如: `en`, `es`,以及 `fr`. - 选择的 ISO 639 - 3 代码,例如: `eng`, `spa`, `yue`,以及 `cmn`. - 区域 `zh` 语言编码,例如 `zh-cn`, `zh-tw`,以及 `zh-hk`. 实时API拒绝不支持或不正确的格式化语言代码. 关键词是提示, 不需要输出。 将每个关键词保留在一条线上, 但不包括 `<`, `>`,车厢返回,或线路种子。如果关键字中包含一个字符,则实时API拒绝更新会话。 `prompt` 超过模型的长度限制。 `gpt-live-transcribe` 用途 `languages` 而不是单数 `language` 字段。不要同时发送。 ## 转过身来 使用( U) `gpt-transcribe` 在实时会话中,只有在承诺的音频转折或需要检测到的语言输出后,您需要特定的转录才能开始。这个专门的工作流程需要WebSocket连接。 何时 `gpt-transcribe` 在实时 API 会话中执行输入转录,或者在专用转录会话中运行,它会自动使用早期转录的转录作为上下文. ```json { "type": "session.update", "session": { "type": "transcription", "audio": { "input": { "format": { "type": "audio/pcm", "rate": 24000 }, "transcription": { "model": "gpt-transcribe" }, "turn_detection": null } } } } ``` 附加音频并发送 `input_audio_buffer.commit`。该模型然后可以在最后完成事件之前发出三角洲记录。其完成事件还包括检测到的语言: ```json { "type": "conversation.item.input_audio_transcription.completed", "item_id": "item_003", "content_index": 0, "transcript": "Bonjour, pouvez-vous m'entendre ?", "languages": [{ "code": "fr" }] } ``` 何时 `gpt-transcribe` 无法做出可靠的语言预测, `languages` 是一个空数组。 `gpt-live-transcribe` 不返回检测到的语言预测。 ### 录制麦克风音频并进行转弯 在 24 kHz 录制单声道 PCM16 音频,在停止麦克风后保持 WebSocket 打开,以便您完成转弯并接收最后的笔录. - 用于需要 `transcriptionModel`,通过 `"gpt-transcribe"`。使用 Linux 并带有 FFmpeg 和一个默认的 ALSA 麦克风。对于 C# , 也安装 `setsid` 从 util-linux. 按 Ctrl+C 停止录制并进行转弯。 - 对于 TypeScript, Go, 和 Ruby, 通过一个与录制功能的开放式转录连接。 使用 FFmpeg 与 ALSA 连接到 TypeScript 或 PortAudio 连接到 Go 和 Ruby 。 在录制后, 发送 `input_audio_buffer.commit`. - 对于 Python , 导入 `asyncio`, `base64`, `json`, `logging`, `websockets`,以及 `sounddevice as sd`设置 `SAMPLE_RATE = 24000` 财务报告和财务报告 `CHUNK_SIZE = 2400`中运行循环,将配置的 WebSocket 作为 ASync 函数 `ws`。在转弯的尽头打破循环并发送 `input_audio_buffer.commit`. ```typescript import { spawn } from "node:child_process"; // Linux example: FFmpeg reads the default ALSA microphone as mono PCM16. // Press Ctrl+C to stop recording and wait for the final transcript. async function recordMicrophone(connection: OpenAIRealtimeWS): Promise<void> { const recorder = spawn( "ffmpeg", [ "-hide_banner", "-loglevel", "error", "-analyzeduration", "0", "-probesize", "32", "-f", "alsa", "-channels", "1", "-sample_rate", "24000", "-i", "default", "-af", "asetnsamples=n=2400:p=1", "-f", "s16le", "-flush_packets", "1", "pipe:1", ], { stdio: ["ignore", "pipe", "pipe"] } ); let stopped = false; let failure: Error | undefined; let diagnostics = ""; recorder.stderr.on("data", (data: Buffer) => { diagnostics = (diagnostics + data.toString()).slice(-4096); }); const closed = new Promise<number | null>((resolve, reject) => { recorder.once("error", reject); recorder.once("close", resolve); }); // Observe rejection immediately, including when spawning the recorder fails. void closed.catch(() => {}); const stop = () => { stopped = true; recorder.kill("SIGINT"); }; const onError = (error: Error) => { failure = error; recorder.kill("SIGKILL"); }; const onClose = () => onError(new Error("Connection closed during microphone capture")); process.on("SIGINT", stop); connection.on("error", onError); connection.socket.on("close", onClose); let pending = Buffer.alloc(0); try { for await (const data of recorder.stdout) { pending = Buffer.concat([pending, data]); while (pending.length >= 4800) { connection.send({ type: "input_audio_buffer.append", audio: pending.subarray(0, 4800).toString("base64"), }); pending = pending.subarray(4800); } if (failure) throw failure; } const code = await closed; if (failure) throw failure; if (!stopped || (code !== 0 && code !== 255)) throw new Error(`Microphone capture failed: ${diagnostics}`); if (pending.length % 2) throw new Error("Incomplete PCM16 sample"); if (pending.length) connection.send({ type: "input_audio_buffer.append", audio: pending.toString("base64"), }); } finally { process.off("SIGINT", stop); connection.off("error", onError); connection.socket.off("close", onClose); recorder.kill("SIGKILL"); await closed.catch(() => {}); } } ``` ```python with sd.InputStream( samplerate=SAMPLE_RATE, channels=1, dtype="int16", blocksize=CHUNK_SIZE ) as stream: while True: # Read a chunk from the microphone in a non-blocking way. audio_chunk, overflowed = await asyncio.to_thread(stream.read, CHUNK_SIZE) if overflowed: print("Audio overflow occurred!") audio_bytes = audio_chunk.tobytes() audio_append_event = { "type": "input_audio_buffer.append", "audio": base64.b64encode(audio_bytes).decode("utf-8"), } try: await ws.send(json.dumps(audio_append_event)) except websockets.ConnectionClosed: logging.info("WebSocket closed gracefully.") break await asyncio.sleep(0) ``` ```go func recordMicrophone(ctx context.Context, connection *realtime.RealtimeConnection) (result error) { // Ctrl+C stops capture; keep the WebSocket alive to receive the transcript. capture, stop := signal.NotifyContext(ctx, os.Interrupt) defer stop() if err := portaudio.Initialize(); err != nil { return err } defer func() { result = errors.Join(result, portaudio.Terminate()) }() samples := make([]int16, 2400) stream, err := portaudio.OpenDefaultStream(1, 0, 24000, len(samples), samples) if err != nil { return err } defer func() { result = errors.Join(result, stream.Close()) }() if err := stream.Start(); err != nil { return err } defer func() { result = errors.Join(result, stream.Stop()) }() pcm := make([]byte, len(samples)*2) for capture.Err() == nil { // Read 100 ms of mono PCM16. Treat input overflow as lost audio, not success. if err := stream.Read(); err != nil { return err } for i, sample := range samples { binary.LittleEndian.PutUint16(pcm[2*i:], uint16(sample)) } send, cancel := context.WithTimeout(ctx, 30*time.Second) err := connection.Send(send, realtime.RealtimeClientEventParamOfInputAudioBufferAppend(base64.StdEncoding.EncodeToString(pcm))) cancel() if err != nil { return err } } return ctx.Err() } ``` ```java import com.openai.client.okhttp.OkHttpClient; import com.openai.core.ClientOptions; import com.openai.helpers.RealtimeConnection; import com.openai.helpers.RealtimeWebSocketOptions; import com.openai.models.realtime.*; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import sun.misc.Signal; import sun.misc.SignalHandler; public final class RealtimeRealtimeTranscriptionMicrophoneExample { public static void transcribeMicrophone(String transcriptionModel) throws Exception { var http = OkHttpClient.builder().build(); var options = ClientOptions.builder().fromEnv().httpClient(http).build(); try (http; var connection = RealtimeConnection.connect( options, RealtimeWebSocketOptions.builder().transcription().build())) { receiveUntil(connection, "session.created", 30); send( connection, RealtimeClientEvent.ofSessionUpdate( SessionUpdateEvent.builder() .session( RealtimeTranscriptionSessionCreateRequest.builder() .audio( RealtimeTranscriptionSessionAudio.builder() .input( RealtimeTranscriptionSessionAudioInput.builder() .format( RealtimeAudioFormats.AudioPcm.builder() .type( RealtimeAudioFormats.AudioPcm.Type.AUDIO_PCM) .rate(RealtimeAudioFormats.AudioPcm.Rate._24000) .build()) .transcription( AudioTranscription.builder() .model(transcriptionModel) .language("en") .build()) .turnDetection( (RealtimeTranscriptionSessionAudioInputTurnDetection) null) .build()) .build()) .build()) .build())); receiveUntil(connection, "session.updated", 30); recordMicrophone(connection); send( connection, RealtimeClientEvent.ofInputAudioBufferCommit( InputAudioBufferCommitEvent.builder().build())); long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(60); String itemID = null; while (true) { var event = receive(connection, deadline); if (event.inputAudioBufferCommitted().isPresent()) { if (itemID != null) throw new IllegalStateException("Duplicate audio commit receipt"); itemID = event.inputAudioBufferCommitted().orElseThrow().itemId(); if (itemID.isBlank()) throw new IllegalStateException("Missing committed item ID"); } if (event.conversationItemInputAudioTranscriptionFailed().isPresent()) { var failed = event.conversationItemInputAudioTranscriptionFailed().orElseThrow(); if (itemID != null && itemID.equals(failed.itemId())) throw new IllegalStateException("Microphone transcription failed"); } if (event.conversationItemInputAudioTranscriptionCompleted().isPresent()) { var completed = event.conversationItemInputAudioTranscriptionCompleted().orElseThrow(); if (itemID != null && itemID.equals(completed.itemId())) { if (completed.contentIndex() != 0 || completed.transcript().isBlank()) throw new IllegalStateException("Missing microphone transcript"); System.out.println(completed.transcript()); return; } } } } finally { options.close(); } } static void recordMicrophone(RealtimeConnection connection) throws Exception { // Linux prerequisite: FFmpeg with ALSA input and an accessible default microphone. // Ctrl+C stops capture without closing the socket needed for the final transcript. var recorder = new ProcessBuilder( "ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "error", "-xerror", "-f", "alsa", "-i", "default", "-ac", "1", "-ar", "24000", "-c:a", "pcm_s16le", "-f", "s16le", "pipe:1") .start(); var stopped = new AtomicBoolean(); var diagnostics = new AtomicReference<byte[]>(new byte[0]); var diagnosticFailure = new AtomicReference<IOException>(); Thread errors = new Thread( () -> { try (var input = recorder.getErrorStream()) { diagnostics.set(input.readNBytes(65537)); if (diagnostics.get().length > 65536) recorder.toHandle().destroy(); } catch (IOException error) { diagnosticFailure.set(error); } }, "microphone-diagnostics"); errors.start(); Signal interrupt = new Signal("INT"); SignalHandler previous; try { previous = Signal.handle( interrupt, signal -> { stopped.set(true); recorder.toHandle().destroy(); }); } catch (RuntimeException | Error failure) { recorder.toHandle().destroyForcibly(); recorder.waitFor(5, TimeUnit.SECONDS); errors.join(5000); throw failure; } int frames = 0; boolean prematureEof = false; try (var input = recorder.getInputStream()) { while (true) { byte[] frame; try { frame = input.readNBytes(4800); } catch (IOException error) { if (stopped.get()) break; throw error; } byte[] samples = completePcm16Samples(frame); if (samples.length > 0) { send( connection, RealtimeClientEvent.ofInputAudioBufferAppend( InputAudioBufferAppendEvent.builder() .audio(Base64.getEncoder().encodeToString(samples)) .build())); frames++; } if (frame.length != 4800) { if (stopped.get()) break; prematureEof = true; break; } } } finally { Signal.handle(interrupt, previous); recorder.toHandle().destroy(); if (!recorder.waitFor(5, TimeUnit.SECONDS)) { recorder.toHandle().destroyForcibly(); if (!recorder.waitFor(5, TimeUnit.SECONDS)) throw new IOException("Microphone recorder did not stop"); } errors.join(5000); if (errors.isAlive()) throw new IOException("Microphone diagnostics did not stop"); } if (prematureEof) { // Report only fixed categories: recorder diagnostics may contain private paths. String detail = new String(diagnostics.get(), StandardCharsets.UTF_8); String category = detail.contains("non monotonically increasing dts") ? "non-monotonic-timestamps" : detail.contains("Unrecognized option") ? "unsupported-option" : detail.contains("Unknown input format") ? "unsupported-input-format" : detail.contains("Permission denied") ? "permission-denied" : detail.contains("Device or resource busy") ? "device-busy" : detail.contains("Input/output error") ? "input-output-error" : detail.isBlank() ? "none" : "other"; throw new IOException( "Microphone ended before Ctrl+C; recorder exit after cleanup=" + recorder.exitValue() + "; diagnostics=" + category + "; diagnostic bytes=" + diagnostics.get().length + "; diagnostic read failed=" + (diagnosticFailure.get() != null)); } if (!stopped.get() || frames == 0) throw new IOException("No microphone audio captured before Ctrl+C"); String messages = new String(diagnostics.get(), StandardCharsets.UTF_8); if (!messages.isBlank()) throw new IOException("Microphone capture failed: " + messages); if (diagnosticFailure.get() != null) throw diagnosticFailure.get(); } // Retry only explicit admission rejections; these guarantee nothing was sent. static void send(RealtimeConnection connection, RealtimeClientEvent event) throws Exception { long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); while (true) { try { connection.send(event); return; } catch (com.openai.core.http.WebSocketWriteNotAttempted.Busy busy) { if (System.nanoTime() >= deadline) throw busy; Thread.sleep(10); } } } static byte[] completePcm16Samples(byte[] frame) { return java.util.Arrays.copyOf(frame, frame.length - frame.length % 2); } static RealtimeServerEvent receive(RealtimeConnection connection, long deadline) throws Exception { var event = connection .receiveAsync() .get(Math.max(0, deadline - System.nanoTime()), TimeUnit.NANOSECONDS); if (event.error().isPresent()) throw new IllegalStateException(event.error().orElseThrow().toString()); return event; } static void receiveUntil(RealtimeConnection connection, String type, int seconds) throws Exception { long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(seconds); while (true) { var event = receive(connection, deadline); if (type.equals("session.created") && event.sessionCreated().isPresent()) return; if (type.equals("session.updated") && event.sessionUpdated().isPresent()) return; } } } ``` ```csharp using 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 OPENAI002 namespace 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 ``` ```ruby require "openai" require "base64" require "ffi-portaudio" def check_audio(result) raise FFI::PortAudio::API.Pa_GetErrorText(result) unless result == :paNoError end def 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) end end ``` ## 久拖不决和准确性 流转转转录交易为记录转录质量提供耐久性。 降低延迟设置可以产生更早的部分文本。 更高的延迟设置在发送文本之前会给模型带来更多的音频上下文, 并可提高字数错误率 。 从设置开始 `audio.input.transcription.delay` 并测试您的真实音频。有用的起点是 : - `minimal` 进行最耐久的、最敏感的互动; - `low` 低度实时字幕; - `medium` 平衡的延迟/准确性权衡; - `high` 准确性大于即时显示; - `xhigh` 当您的工作流程可以容忍更多语境中最长时间的延迟时。 以毫秒计的确切延迟可以因模型配置而异,因此基准以具有代表性的音频而不是假设每个关卡的固定时间. 不要单独从合成音频中选择一个设置 。 用具有代表性的麦克风、 电话音频、 重音、 背景噪声、 代码交换、 域名词汇和长会话进行测试 。 ## 处理信心、时间戳和扬声器标签 `gpt-live-transcribe` 不返回文字级别的时间戳、扬声器标签或复制信任分数。如果应用程序需要时间戳或扬声器标签,请使用兼容的标签。 [存档转录](https://developers.openai.com/api/docs/guides/speech-to-text) 模型或添加应用程序级回落。 ## 生产清单 - 在调谐前选择一个目标延迟和准确阈值. - 检测真实制作的音频,不仅仅是干净的样本. - 测试每种目标语言. - 将数字、日期、货币、电子邮件地址、产品名称和域名包含在您的 eval 集中。 - 音轨为空,截断,除词错误率外还有延迟的音符. - 决定您的 UI 当后面的 deltas 校正先前的文本时, 如何修改部分文本 。 - 使用( U) `item_id` 订购和核对最后记录。 - 保留一个不支持的时间戳,扬声器标签或信任字段的倒置路径. ## 相关指南 [实时和音频概览](https://developers.openai.com/api/docs/guides/realtime) 比较语音代理,翻译,和抄写会话. [实时翻译](https://developers.openai.com/api/docs/guides/realtime-translation) 用专门的翻译会话翻译现场演讲. [WebSocket 连接](https://developers.openai.com/api/docs/guides/voice-websockets?api=realtime) 通过服务器侧媒体管道流出原始音频 。 [语音活动检测](https://developers.openai.com/api/docs/guides/realtime-vad) 配置直播音频流的回合检测 。

查看原始来源