Class: ElevenlabsClient::WebSocketTextToSpeech

Inherits:
Object
  • Object
show all
Defined in:
lib/elevenlabs_client/endpoints/websocket_text_to_speech.rb

Instance Method Summary collapse

Constructor Details

#initialize(client) ⇒ WebSocketTextToSpeech

Returns a new instance of WebSocketTextToSpeech.



8
9
10
11
# File 'lib/elevenlabs_client/endpoints/websocket_text_to_speech.rb', line 8

def initialize(client)
  @client = client
  @base_url = client.base_url.gsub('https://', 'wss://').gsub('http://', 'ws://')
end

Instance Method Details

#connect_multi_stream_input(voice_id, **options) ⇒ WebSocket::Client::Simple::Client Also known as: connect_multi_context

Creates a WebSocket connection for multi-context text-to-speech streaming Documentation: https://elevenlabs.io/docs/api-reference/websockets/multi-context

Parameters:

  • voice_id (String)

    The unique identifier for the voice

  • options (Hash)

    Optional parameters (same as connect_stream_input)

Returns:

  • (WebSocket::Client::Simple::Client)

    WebSocket client instance



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/elevenlabs_client/endpoints/websocket_text_to_speech.rb', line 58

def connect_multi_stream_input(voice_id, **options)
  endpoint = "/v1/text-to-speech/#{voice_id}/multi-stream-input"
  
  # Build query parameters in the same order as provided in options
  allowed_keys = [:model_id, :language_code, :enable_logging, :enable_ssml_parsing, :output_format, :inactivity_timeout, :sync_alignment, :auto_mode, :apply_text_normalization, :seed]
  pairs = []
  options.each do |k, v|
    next unless allowed_keys.include?(k)
    next if v.nil?
    next if (k == :language_code || k == :apply_text_normalization) && v.to_s.empty?
    pairs << [k, v]
  end
  if pairs.any?
    query_string = pairs.map { |k, v| "#{k}=#{v}" }.join("&")
    endpoint += "?#{query_string}"
  end
  
  url = "#{@base_url}#{endpoint}"
  headers = { "xi-api-key" => @client.api_key }
  
  WebSocket::Client::Simple.connect(url, headers: headers)
end

#connect_stream_input(voice_id, **options) ⇒ WebSocket::Client::Simple::Client Also known as: connect_single_stream

Creates a WebSocket connection for real-time text-to-speech streaming Documentation: https://elevenlabs.io/docs/api-reference/websockets/text-to-speech

Parameters:

  • voice_id (String)

    The unique identifier for the voice

  • options (Hash)

    Optional parameters

Options Hash (**options):

  • :model_id (String)

    The model ID to use

  • :language_code (String)

    ISO 639-1 language code

  • :enable_logging (Boolean)

    Enable logging (default: true)

  • :enable_ssml_parsing (Boolean)

    Enable SSML parsing (default: false)

  • :output_format (String)

    Output audio format

  • :inactivity_timeout (Integer)

    Timeout in seconds (default: 20, max: 180)

  • :sync_alignment (Boolean)

    Include timing data (default: false)

  • :auto_mode (Boolean)

    Reduce latency mode (default: false)

  • :apply_text_normalization (String)

    Text normalization ("auto", "on", "off")

  • :seed (Integer)

    Deterministic sampling seed (0-4294967295)

Returns:

  • (WebSocket::Client::Simple::Client)

    WebSocket client instance



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/elevenlabs_client/endpoints/websocket_text_to_speech.rb', line 29

def connect_stream_input(voice_id, **options)
  endpoint = "/v1/text-to-speech/#{voice_id}/stream-input"
  
  # Build query parameters in the same order as provided in options
  allowed_keys = [:model_id, :language_code, :enable_logging, :enable_ssml_parsing, :output_format, :inactivity_timeout, :sync_alignment, :auto_mode, :apply_text_normalization, :seed]
  pairs = []
  options.each do |k, v|
    next unless allowed_keys.include?(k)
    next if v.nil?
    next if (k == :language_code || k == :apply_text_normalization) && v.to_s.empty?
    pairs << [k, v]
  end
  if pairs.any?
    query_string = pairs.map { |k, v| "#{k}=#{v}" }.join("&")
    endpoint += "?#{query_string}"
  end
  
  url = "#{@base_url}#{endpoint}"
  headers = { "xi-api-key" => @client.api_key }
  
  WebSocket::Client::Simple.connect(url, headers: headers)
end

#send_close_connection(ws) ⇒ Object

Helper method to close connection for single stream

Parameters:

  • ws (WebSocket::Client::Simple::Client)

    WebSocket client



113
114
115
116
# File 'lib/elevenlabs_client/endpoints/websocket_text_to_speech.rb', line 113

def send_close_connection(ws)
  message = { text: "" }
  ws.send(message.to_json)
end

#send_close_context(ws, context_id) ⇒ Object

Helper method to close a specific context

Parameters:

  • ws (WebSocket::Client::Simple::Client)

    WebSocket client

  • context_id (String)

    Context identifier



177
178
179
180
181
182
183
184
# File 'lib/elevenlabs_client/endpoints/websocket_text_to_speech.rb', line 177

def send_close_context(ws, context_id)
  message = {
    context_id: context_id,
    close_context: true
  }
  
  ws.send(message.to_json)
end

#send_close_socket(ws) ⇒ Object

Helper method to close the entire socket

Parameters:

  • ws (WebSocket::Client::Simple::Client)

    WebSocket client



200
201
202
203
# File 'lib/elevenlabs_client/endpoints/websocket_text_to_speech.rb', line 200

def send_close_socket(ws)
  message = { close_socket: true }
  ws.send(message.to_json)
end

#send_flush_context(ws, context_id) ⇒ Object

Helper method to flush a context

Parameters:

  • ws (WebSocket::Client::Simple::Client)

    WebSocket client

  • context_id (String)

    Context identifier



165
166
167
168
169
170
171
172
# File 'lib/elevenlabs_client/endpoints/websocket_text_to_speech.rb', line 165

def send_flush_context(ws, context_id)
  message = {
    context_id: context_id,
    flush: true
  }
  
  ws.send(message.to_json)
end

#send_initialize_connection(ws, **options) ⇒ Object

Helper method to send initialization message for single stream

Parameters:

  • ws (WebSocket::Client::Simple::Client)

    WebSocket client

  • options (Hash)

    Initialization options

Options Hash (**options):

  • :text (String)

    Initial text (usually a space)

  • :voice_settings (Hash)

    Voice settings hash

  • :xi_api_key (String)

    API key (will use client's key if not provided)



87
88
89
90
91
92
93
94
95
# File 'lib/elevenlabs_client/endpoints/websocket_text_to_speech.rb', line 87

def send_initialize_connection(ws, **options)
  message = {
    text: options[:text] || " ",
    voice_settings: options[:voice_settings] || {},
    xi_api_key: options[:xi_api_key] || @client.api_key
  }
  
  ws.send(message.to_json)
end

#send_initialize_connection_multi(ws, context_id, **options) ⇒ Object

Helper method to send initialization message for multi-context stream

Parameters:

  • ws (WebSocket::Client::Simple::Client)

    WebSocket client

  • context_id (String)

    Context identifier

  • options (Hash)

    Initialization options



122
123
124
125
126
127
128
129
130
# File 'lib/elevenlabs_client/endpoints/websocket_text_to_speech.rb', line 122

def send_initialize_connection_multi(ws, context_id, **options)
  message = {
    text: options[:text] || " ",
    voice_settings: options[:voice_settings] || {},
    context_id: context_id
  }
  
  ws.send(message.to_json)
end

#send_initialize_context(ws, context_id, **options) ⇒ Object

Helper method to initialize a new context in multi-stream

Parameters:

  • ws (WebSocket::Client::Simple::Client)

    WebSocket client

  • context_id (String)

    Context identifier

  • options (Hash)

    Context options



136
137
138
139
140
141
142
143
144
145
# File 'lib/elevenlabs_client/endpoints/websocket_text_to_speech.rb', line 136

def send_initialize_context(ws, context_id, **options)
  message = {
    context_id: context_id,
    voice_settings: options[:voice_settings] || {}
  }
  message[:model_id] = options[:model_id] if options[:model_id]
  message[:language_code] = options[:language_code] if options[:language_code]
  
  ws.send(message.to_json)
end

#send_keep_context_alive(ws, context_id) ⇒ Object

Helper method to keep a context alive

Parameters:

  • ws (WebSocket::Client::Simple::Client)

    WebSocket client

  • context_id (String)

    Context identifier



189
190
191
192
193
194
195
196
# File 'lib/elevenlabs_client/endpoints/websocket_text_to_speech.rb', line 189

def send_keep_context_alive(ws, context_id)
  message = {
    context_id: context_id,
    keep_context_alive: true
  }
  
  ws.send(message.to_json)
end

#send_text(ws, text, **options) ⇒ Object

Helper method to send text for single stream

Parameters:

  • ws (WebSocket::Client::Simple::Client)

    WebSocket client

  • text (String)

    Text to convert to speech

  • options (Hash)

    Optional parameters

Options Hash (**options):

  • :try_trigger_generation (Boolean)

    Try to trigger generation

  • :voice_settings (Hash)

    Voice settings override



103
104
105
106
107
108
109
# File 'lib/elevenlabs_client/endpoints/websocket_text_to_speech.rb', line 103

def send_text(ws, text, **options)
  message = { text: text }
  message[:try_trigger_generation] = options[:try_trigger_generation] unless options[:try_trigger_generation].nil?
  message[:voice_settings] = options[:voice_settings] if options[:voice_settings]
  
  ws.send(message.to_json)
end

#send_text_multi(ws, context_id, text, **options) ⇒ Object

Helper method to send text for multi-context stream

Parameters:

  • ws (WebSocket::Client::Simple::Client)

    WebSocket client

  • context_id (String)

    Context identifier

  • text (String)

    Text to convert to speech

  • options (Hash)

    Optional parameters



152
153
154
155
156
157
158
159
160
# File 'lib/elevenlabs_client/endpoints/websocket_text_to_speech.rb', line 152

def send_text_multi(ws, context_id, text, **options)
  message = {
    text: text,
    context_id: context_id
  }
  message[:flush] = options[:flush] unless options[:flush].nil?
  
  ws.send(message.to_json)
end

#stream_text_to_speech(voice_id, text_chunks, **options, &block) ⇒ Object

Convenience method to create a complete streaming session

Parameters:

  • voice_id (String)

    The unique identifier for the voice

  • text_chunks (Array<String>)

    Array of text chunks to stream

  • options (Hash)

    Connection and voice options

  • block (Proc)

    Block to handle audio chunks



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
# File 'lib/elevenlabs_client/endpoints/websocket_text_to_speech.rb', line 210

def stream_text_to_speech(voice_id, text_chunks, **options, &block)
  ws = connect_stream_input(voice_id, **options)
  
  ws.on :open do
    # Initialize connection
    send_initialize_connection(ws, **options)
    
    # Send text chunks
    text_chunks.each_with_index do |chunk, index|
      send_text(ws, chunk, try_trigger_generation: (index == text_chunks.length - 1))
    end
    
    # Close connection
    send_close_connection(ws)
  end
  
  ws.on :message do |msg|
    data = JSON.parse(msg.data)
    if data['audio'] && block_given?
      # Decode base64 audio and yield to block
      audio_data = Base64.decode64(data['audio'])
      block.call(audio_data, data)
    end
  end
  
  ws.on :error do |e|
    raise APIError, "WebSocket error: #{e.message}"
  end
  
  ws
end