Skip to content

Instantly share code, notes, and snippets.

@rocLv
Last active April 18, 2017 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rocLv/8c7e5367c0cd1b498d2d4f73fc3e0990 to your computer and use it in GitHub Desktop.
Save rocLv/8c7e5367c0cd1b498d2d4f73fc3e0990 to your computer and use it in GitHub Desktop.
require 'curb'
require "json"
require "base64"
require "net/http"
require "uri"
CUID = "8132533";
CLIENT_ID = "your_client_id";
CLIENT_SECRET = "your_client_secret";
AUTH_URL = "https://openapi.baidu.com/oauth/2.0/token"
AUTH_PARAMS = {
grant_type: "client_credentials",
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET
}
BAIDU_VOP = "http://vop.baidu.com/server_api";
PCM_FILE = "ActionController002.raw"
DEBUG = true
def file_size
File.new(PCM_FILE).stat.size
end
def speech
Base64.encode64(IO.read(PCM_FILE)).gsub(/\n/, '')
end
puts speech if DEBUG
puts "speech is ^" if DEBUG
def token
response = Curl.get AUTH_URL, AUTH_PARAMS
JSON.parse(response.body)["access_token"]
end
puts token if DEBUG
def vop_params
{
"format" => "pcm",
"rate" => 8000,
"channel" => 1,
"lan" => "en",
"token" => token,
"cuid" => CUID,
"len" => file_size,
"speech" => speech
}
end
def content_length
JSON.generate(vop_params.to_json).size
end
fp = open "json_array.txt", "wb"
fp.puts vop_params.to_json
fp.close
#result = Curl.post BAIDU_VOP, JSON.generate(vop_params) do |http|
# http.headers = {
# # "Content-length": content_length,
# "Content-Type": "application/json; charset=utf-8"
# }
# http.verbose = true if DEBUG
#end
#puts result.status
#puts result.body
post_json = JSON.generate(vop_params)
http = Net::HTTP.new('vop.baidu.com', 80)
http_resp = http.post('/server_api', post_json, {'Content-Type' =>'application/json'})
puts http_resp.body
#uri = URI.parse BAIDU_VOP
#header = {
# "Content-length": file_size.to_s,
# "Content-Type": "application/json; charset=utf-8"
#}
#
#request = Net::HTTP::Post.new(uri.request_uri, header)
#request.body = vop_params.to_json
#http = Net::HTTP.new uri.host, uri.port
#http.read_timeout = 300
#response = http.request(request)
#puts request.body
#puts response.body
@rocLv
Copy link
Author

rocLv commented Apr 18, 2017

百度语音API ruby调用示例

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment