1- import { ReactNode , useRef , useState } from "react"
1+ import { ReactNode , useCallback , useRef , useState } from "react"
22import { RealtimeSessionView } from "../components/RealtimeSessionView"
33import { RealtimeClient } from "@tsorta/browser/WebRTC"
44import { PageProps } from "./props"
@@ -14,30 +14,40 @@ export function WebRTCExample({
1414
1515 const [ client , setClient ] = useState < RealtimeClient | undefined > ( undefined )
1616
17- async function startSession ( ) : Promise < void > {
18- if ( ! apiKey ) {
19- throw new Error ( "API key is required" )
20- }
21- if ( ! audioElementRef ?. current ) {
22- throw new Error ( "Audio element not found" )
23- }
24-
25- const client = new RealtimeClient (
26- navigator ,
27- ( ) => apiKey ,
28- audioElementRef . current ,
29- { model : "gpt-4o-realtime-preview-2024-12-17" }
30- )
31- client . on ( "event" , onServerEvent )
32- setClient ( client )
33- await client . start ( )
34- onSessionStatusChanged ( "recording" )
35- }
36-
37- async function stopSession ( ) : Promise < void > {
38- await client ?. stop ( )
39- onSessionStatusChanged ( "stopped" )
40- }
17+ const startSession = useCallback (
18+ async function startSession ( ) : Promise < void > {
19+ if ( ! apiKey ) {
20+ throw new Error ( "API key is required" )
21+ }
22+ if ( ! audioElementRef ?. current ) {
23+ throw new Error ( "Audio element not found" )
24+ }
25+
26+ const client = new RealtimeClient (
27+ navigator ,
28+ ( ) => apiKey ,
29+ audioElementRef . current ,
30+ { model : "gpt-4o-realtime-preview-2024-12-17" }
31+ )
32+ setClient ( client )
33+
34+ client . addEventListener ( "serverEvent" , ( event ) => {
35+ onServerEvent ( event )
36+ } )
37+ await client . start ( )
38+
39+ onSessionStatusChanged ( "recording" )
40+ } ,
41+ [ apiKey , audioElementRef , onServerEvent , onSessionStatusChanged , navigator ]
42+ )
43+
44+ const stopSession = useCallback (
45+ async function stopSession ( ) : Promise < void > {
46+ await client ?. stop ( )
47+ onSessionStatusChanged ( "stopped" )
48+ } ,
49+ [ client , onSessionStatusChanged ]
50+ )
4151
4252 return (
4353 < div className = "container" >
@@ -46,7 +56,7 @@ export function WebRTCExample({
4656 This example demonstrates how to use the OpenAI Realtime API directly.
4757 It is using the TypeScript client from the article{ " " }
4858 < a href = "https://scott.willeke.com/ai-typescript-client-for-openai-realtime-api" >
49- AI Learns to Listen: TypeScript Client for OpenAI’ s Realtime API
59+ AI Learns to Listen: TypeScript Client for OpenAI' s Realtime API
5060 </ a > { " " }
5161 by Scott Willeke.
5262 </ p >
0 commit comments