Class: Ultrasafeai::Audio::Stream::AudioStreamSession

Inherits:
Object
  • Object
show all
Defined in:
lib/ultrasafeai/audio/stream/audio_stream_session.rb

Overview

An active ASR streaming session returned by StreamClient#connect.

Subscribe to server events with #on, send PCM audio with #send, and call #close when done.

Event handler arguments differ by event:

- ASR events (e.g. "transcript"): handler receives the full event Hash
- "close": handler receives (code, reason)
- "ws_error": handler receives (exception)
- "parse_error": handler receives (exception, raw_string)

Constant Summary collapse

DISCRIMINANT =
"type".freeze

Instance Method Summary collapse

Constructor Details

#initialize(ws) ⇒ AudioStreamSession

Returns a new instance of AudioStreamSession.



28
29
30
31
32
33
# File 'lib/ultrasafeai/audio/stream/audio_stream_session.rb', line 28

def initialize(ws)
  @ws = ws
  @handlers = {}
  @handlers_mutex = Mutex.new
  @closed = false
end

Instance Method Details

#closeObject

Close the session gracefully.



59
60
61
62
# File 'lib/ultrasafeai/audio/stream/audio_stream_session.rb', line 59

def close
  @closed = true
  @ws.close
end

#emit(event, *args) ⇒ Object



65
66
67
68
# File 'lib/ultrasafeai/audio/stream/audio_stream_session.rb', line 65

def emit(event, *args)
  handlers = @handlers_mutex.synchronize { (@handlers[event.to_s] || []).dup }
  handlers.each { |h| h.call(*args) }
end

#off(event, &handler) ⇒ Object

Unsubscribe a handler (by object identity). Returns self for chaining.



45
46
47
48
49
50
# File 'lib/ultrasafeai/audio/stream/audio_stream_session.rb', line 45

def off(event, &handler)
  @handlers_mutex.synchronize do
    @handlers[event.to_s]&.delete_if { |h| h == handler }
  end
  self
end

#on(event, &handler) ⇒ Object

Subscribe to a named event. Returns self for chaining.



36
37
38
39
40
41
42
# File 'lib/ultrasafeai/audio/stream/audio_stream_session.rb', line 36

def on(event, &handler)
  @handlers_mutex.synchronize do
    @handlers[event.to_s] ||= []
    @handlers[event.to_s] << handler
  end
  self
end

#send(audio) ⇒ Object

Send a raw PCM audio frame to the ASR engine.



53
54
55
56
# File 'lib/ultrasafeai/audio/stream/audio_stream_session.rb', line 53

def send(audio)
  raise ConnectionClosedError if @closed
  @ws.send(audio, type: :binary)
end