Skip to content

Instantly share code, notes, and snippets.

@rewonc
Created September 18, 2014 00:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rewonc/0024ec71bb589be18bd7 to your computer and use it in GitHub Desktop.
Save rewonc/0024ec71bb589be18bd7 to your computer and use it in GitHub Desktop.
Play Google Translate's text to speech audio directly on your rails webpage
#This will allow you to serve google TTS audio from your own domain, allowing you to use it in the source for HTML5 audio tags.
#tts_controller.rb
class TtsController < ApplicationController
def pipe
queryString = params[:query_string] #.gsub(. . ., '')
lang = params[:lang] #Language code; see https://sites.google.com/site/tomihasa/google-language-codes
require 'net/http'
url = URI.parse('http://translate.google.com/translate_tts?ie=UTF-8&tl=' + lang + '&q=' + URI::encode(queryString))
req = Net::HTTP::Get.new(url.to_s)
res = Net::HTTP.start(url.host, url.port) {|http|
http.request(req)
}
send_data(res.body, :disposition => "inline", :filename => "sound.mp3", :type => "audio/mpeg")
end
end
#routes.rb
scope :api do
get "/tts/:lang/:query_string/" => "tts#pipe"
end
#javascript on your page
=begin
var audioElement = document.createElement('audio');
var playAudio = function (string, lang) {
audioElement.setAttribute('src', 'api/tts/' + lang + '/' + encodeURIComponent(string)
}
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment