Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Google Speech
# encoding: UTF-8
#
# Example of usage:
# 1.9.3p125 :003 > t = GoogleSpeech.load "#{Dir.home}/text.txt"
# => #<GoogleSpeech:0x007f89e38ba690 @text="Hello World it's just a text file. Hey yey!!!", @lang="en">
# 1.9.3p125 :004 > t.save("out.mp3")
# => "out.mp3"
#
# 1.9.3p125 :005 > f = GoogleSpeech.new "Thats shit but I love it"
# => #<GoogleSpeech:0x007f89e385f150 @text="Thats shit but I love it", @lang="en">
# 1.9.3p125 :006 > f.save('out.mp3')
# => "out.mp3"
#
require 'net/http'
class GoogleSpeech
GOOGLE_TRANSLATE_URL = 'http://translate.google.com/translate_tts'
attr_accessor :text, :lang
def initialize(text, lang = 'en')
@text = text
@lang = lang
end
def self.load(file_path, lang = 'en')
f = File.open(file_path)
self.new f.read.force_encoding(Encoding::UTF_8), lang
end
def save(file_path)
uri = URI(GOOGLE_TRANSLATE_URL)
attempts = text.length / 99.0
starts = 0
ar = response = []
attempts.ceil.times do
ends = starts + 99
ar << text[starts...ends]
starts = ends
end
ar.each do |q|
uri.query = URI.encode_www_form({ ie: 'UTF-8', q: q, tl: lang, total: 1, idx: 5, textlen: q.length, prev: 'input' })
res = Net::HTTP.get_response(uri)
response << res.body.force_encoding(Encoding::UTF_8) if res.is_a?(Net::HTTPSuccess)
end
File.open(file_path, 'wb') do |f|
f.write response.join
return f.path
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment