Created
September 18, 2014 00:19
-
-
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 file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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