Text.to_speech through tts-api.com

This extremely simple Ruby module extends the String class by adding a to_speech method, so text.to_speech will perform a request to Text-to-Speech API which produces a remote mp3 file that will be downloaded to the current directory (curl needed):

  • text.to_speechtext.mp3

Usage

#!/usr/bin/env ruby
require_relative 'tts'
class String
include TTS::String
end
"fuck yeah".to_speech
view raw tts-usage.rb hosted with ❤ by GitHub
#!/usr/bin/env ruby
# string.to_speech through tts-api.com
require 'net/http'
SERVICE_URI_FORMAT = "http://tts-api.com/tts.mp3?q=%s"
module TTS
class Speech
def initialize text
response = get_response(SERVICE_URI_FORMAT % text.to_url)
@text = text
@location = response['location']
@filename = text.to_filename('mp3')
end
def to_mp3
download_here @location, @filename
end
def to_s
[@text, @location, @filename].join(' -> ')
end
private
def get_response service_uri
Net::HTTP.get_response(URI.parse(service_uri))
end
def download_here url, filename
system "curl -o #{filename} #{url}"
end
end
module String
def to_speech
speech = Speech.new(self)
puts speech
speech.to_mp3
end
def to_url
gsub(' ', '+').safe
end
def to_filename extension = 'bin'
[(gsub(' ', '_')).safe, extension].join('.')
end
def safe
downcase.strip.gsub(/[^\w-]/, '')
end
end
end
view raw tts.rb hosted with ❤ by GitHub

Code

#!/usr/bin/env ruby
require_relative 'tts'
class String
include TTS::String
end
"fuck yeah".to_speech
view raw tts-usage.rb hosted with ❤ by GitHub
#!/usr/bin/env ruby
# string.to_speech through tts-api.com
require 'net/http'
SERVICE_URI_FORMAT = "http://tts-api.com/tts.mp3?q=%s"
module TTS
class Speech
def initialize text
response = get_response(SERVICE_URI_FORMAT % text.to_url)
@text = text
@location = response['location']
@filename = text.to_filename('mp3')
end
def to_mp3
download_here @location, @filename
end
def to_s
[@text, @location, @filename].join(' -> ')
end
private
def get_response service_uri
Net::HTTP.get_response(URI.parse(service_uri))
end
def download_here url, filename
system "curl -o #{filename} #{url}"
end
end
module String
def to_speech
speech = Speech.new(self)
puts speech
speech.to_mp3
end
def to_url
gsub(' ', '+').safe
end
def to_filename extension = 'bin'
[(gsub(' ', '_')).safe, extension].join('.')
end
def safe
downcase.strip.gsub(/[^\w-]/, '')
end
end
end
view raw tts.rb hosted with ❤ by GitHub
← Articles archive