Class: AzureTTS::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/azure_tts.rb

Instance Method Summary collapse

Constructor Details

#initialize(api_key = nil, region = nil) ⇒ Client

Returns a new instance of Client.

Raises:



30
31
32
33
34
35
# File 'lib/azure_tts.rb', line 30

def initialize(api_key = nil, region = nil)
  @api_key = api_key || AzureTTS.configuration.api_key
  @region = region || AzureTTS.configuration.region
  raise Error, "API key and region must be set" if @api_key.nil? || @region.nil?
  @access_token = fetch_access_token
end

Instance Method Details

#speak(text, voice_options = {}) ⇒ Object



37
38
39
# File 'lib/azure_tts.rb', line 37

def speak(text, voice_options = {})
  tts_request(text, voice_options)
end

#speak_file(text, output_file = "output.wav", voice_options = {}) ⇒ Object



41
42
43
44
45
# File 'lib/azure_tts.rb', line 41

def speak_file(text, output_file = "output.wav", voice_options = {})
  audio_data = tts_request(text, voice_options)
  File.open(output_file, 'wb') { |file| file.write(audio_data) }
  output_file
end

#speak_to_active_storage(text, attachment, voice_options = {}) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/azure_tts.rb', line 47

def speak_to_active_storage(text, attachment, voice_options = {})
  audio_data = speak(text, voice_options)
  temp_file = Tempfile.new(['azure_tts', '.wav'])
  temp_file.binmode
  temp_file.write(audio_data)
  temp_file.rewind

  attachment.attach(
    io: File.open(temp_file.path),
    filename: "tts_output_#{Time.now.to_i}.wav",
    content_type: 'audio/wav'
  )
ensure
  temp_file&.close
  temp_file&.unlink
end