Class: Telnyx::Lib::WebSocket::TextToSpeechWS

Inherits:
Base
  • Object
show all
Includes:
Enumerable
Defined in:
lib/telnyx/lib/websocket/text_to_speech_ws.rb

Overview

WebSocket client for Text-to-Speech (TTS) streaming synthesis.

This client establishes a WebSocket connection to the Telnyx TTS API for real-time speech synthesis. Text input events are sent as JSON and audio chunks are received as events.

Example usage with event callbacks:

client = Telnyx::Client.new(api_key: ENV["TELNYX_API_KEY"])

ws = Telnyx::Lib::WebSocket::TextToSpeechWS.new(client, {
  voice: "telnyx.NaturalHD.Alloy"
})

ws.on(:audio_chunk) do |event|
  audio = event.decode_audio
  # Process audio chunk
end

ws.on(:final) do |event|
  puts "Synthesis complete"
end

ws.wait_for_open
ws.send({ type: "text", text: "Hello, world!" })
ws.send({ type: "flush" })

Example usage with Enumerable pattern:

ws.each do |msg|
  case msg.type
  when :message
    event = msg.message
    if event.audio_chunk?
      # Process audio
    end
  when :error
    puts "Error: #{msg.error.message}"
  when :close
    break
  end
end

Constant Summary collapse

API_PATH =

The WebSocket API path for TTS

"/v2/text-to-speech/speech"

Constants inherited from Base

Base::CLOSED, Base::CLOSING, Base::CONNECTING, Base::OPEN

Instance Attribute Summary collapse

Attributes inherited from Base

#ready_state, #url

Instance Method Summary collapse

Methods inherited from Base

#close, #closed?, #connecting?, #off, #on, #open?, #wait_for_open

Constructor Details

#initialize(client, params = nil, options = {}) ⇒ TextToSpeechWS

Create a new TTS WebSocket connection.

Parameters:

  • client (Telnyx::Client)

    The Telnyx client

  • params (Hash, TextToSpeechStreamParams, nil) (defaults to: nil)

    Stream configuration parameters

  • options (Hash) (defaults to: {})

    Additional WebSocket options

Options Hash (options):

  • :headers (Hash)

    Additional HTTP headers



78
79
80
81
82
83
84
85
86
87
88
# File 'lib/telnyx/lib/websocket/text_to_speech_ws.rb', line 78

def initialize(client, params = nil, options = {})
  super()
  @client = client
  @params = normalize_params(params)
  @options = options
  @stream_queue = nil # Will be a ::Queue
  @streaming = false

  @url = build_url(client, API_PATH, @params&.to_hash)
  connect
end

Instance Attribute Details

#clientTelnyx::Client (readonly)

Returns The Telnyx client.

Returns:



67
68
69
# File 'lib/telnyx/lib/websocket/text_to_speech_ws.rb', line 67

def client
  @client
end

#paramsTextToSpeechStreamParams? (readonly)

Returns The stream parameters.

Returns:



70
71
72
# File 'lib/telnyx/lib/websocket/text_to_speech_ws.rb', line 70

def params
  @params
end

Instance Method Details

#each {|StreamMessage| ... } ⇒ Enumerator

Iterate over WebSocket events using the Enumerable pattern.

This provides an alternative to the callback-based ‘.on()` API. The iterator yields StreamMessage structs with :type, :message, and :error.

Example:

ws.each do |msg|
  case msg.type
  when :message
    puts msg.message.type
  when :close
    break
  end
end

rubocop:disable Lint/UnusedMethodArgument

Yields:

Yield Parameters:

  • msg (StreamMessage)

    The stream message

  • msg.type (Symbol)

    One of :connecting, :open, :closing, :close, :message, :error

  • msg.message (TtsServerEvent, nil)

    The parsed event (for :message type)

  • msg.error (WebSocketError, nil)

    The error (for :error type)

Returns:

  • (Enumerator)

    If no block given



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
# File 'lib/telnyx/lib/websocket/text_to_speech_ws.rb', line 138

def each(&block)
  return to_enum(:each) unless block_given?
  # rubocop:enable Lint/UnusedMethodArgument

  @stream_queue = ::Queue.new
  @streaming = true

  # Set up event forwarding
  setup_streaming

  # Yield initial state
  case @ready_state
  when CONNECTING
    yield(StreamMessage.new(type: :connecting))
  when OPEN
    yield(StreamMessage.new(type: :open))
  when CLOSING
    yield(StreamMessage.new(type: :closing))
  when CLOSED
    yield(StreamMessage.new(type: :close))
    return
  end

  # Process events from the queue
  loop do
    msg = @stream_queue.pop
    break if msg.nil? || (msg.type == :close)

    yield(msg)

    break if msg.type == :close
  end
ensure
  @streaming = false
  @stream_queue = nil
end

#send(event) ⇒ void

This method returns an undefined value.

Send a text input event to the server for synthesis.

Event types:

  • { type: “text”, text: “Hello” } - Add text to synthesize

  • { type: “flush” } - Flush buffered text and generate audio

  • { type: “close” } - Signal end of input

Parameters:

  • event (Hash)

    The event to send

Options Hash (event):

  • :type (String)

    Event type (“text”, “flush”, “close”)

  • :text (String)

    The text to synthesize (for type: “text”)

Raises:



102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/telnyx/lib/websocket/text_to_speech_ws.rb', line 102

def send(event)
  unless open?
    raise WebSocketError.new("Cannot send: WebSocket is not open")
  end

  begin
    json_data = event.is_a?(String) ? event : JSON.generate(event)
    @socket.send(json_data, type: :text)
  rescue StandardError => e
    emit_error(nil, "could not send data", e)
  end
end

#streamEnumerator

Alias for each - provides async iterator semantics

Returns:

  • (Enumerator)


178
179
180
# File 'lib/telnyx/lib/websocket/text_to_speech_ws.rb', line 178

def stream
  each
end