class BaiduAi::SpeechSynthesizer

Public Class Methods

speak(cuid, text) click to toggle source
# File lib/baidu_ai/speech_synthesis/speech_synthesizer.rb, line 9
def self.speak cuid, text
  file_name = get_baidu_ai_speech cuid, text
  system "#{play_command} #{file_name}"
  File.delete file_name
end

Private Class Methods

baidu_ai_speech(cuid, text, spd = 5, pit = 5) click to toggle source
# File lib/baidu_ai/speech_synthesis/speech_synthesizer.rb, line 32
def self.baidu_ai_speech(cuid, text, spd = 5, pit = 5)
  uri = URI.parse("http://tsn.baidu.com/text2audio?")
  if BaiduAi.debug_mode && BaiduAi.logger
    BaiduAi.logger.debug "Requesting uri #{uri}..."
  end
  req = Net::HTTP::Post.new(uri)
  res = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
    req.set_form_data({
        "lan" => "zh",
        "ctp" => "1",
        "cuid" => cuid,
        "tok" => BaiduAi::AccessTokenManager.instance.get_access_token,
        "tex" => text,
        "spd" => spd,
        "pit" => pit
    })
    http.request req
  end
end
get_baidu_ai_speech(cuid, text) click to toggle source
# File lib/baidu_ai/speech_synthesis/speech_synthesizer.rb, line 19
def self.get_baidu_ai_speech cuid, text
  response = baidu_ai_speech cuid, text
  time = Time.now.strftime '%Y%m%d%H%M%S' + rand(10).to_s
  if !File.directory?@speech_dir
    Dir::mkdir(@speech_dir)
  end
  file_name = @speech_dir + time + ".mp3"
  speech = File.new(file_name, "w+")
  speech.puts(response.body)
  speech.close
  file_name
end
play_command() click to toggle source
# File lib/baidu_ai/speech_synthesis/speech_synthesizer.rb, line 52
def self.play_command
  if BaiduAi::OS.mac?
    return 'afplay'
  end
  'play'
end