百度API文档网址为:http://yuyin.baidu.com/docs/asr/57
百度识别出现参数错误:3300 输入参数不正确
可能原因:
1、base64EncodedStringWithOptions(.Encoding64CharacterLineLength)会加”\r\n”
1 |
NSString.stringByReplacingOccurrencesOfString("\r\n", withString: "") |
2、Alamofire 的JSON会把”/”转义成”\/”
如何实现呢?
方法一:使用BASE64编码
要自己构造JSON,不能用NSJSONSerialization…然后网络请求库用其他的,太麻烦>_<
方法二、不使用BASE64编码
1 2 |
import Alamofire import SwiftyJSON |
获取token
1 2 3 4 5 6 7 8 9 10 11 12 |
let parameters=[ "grant_type":"client_credentials", "client_id":"*****************", "client_secret":"******************", ] Alamofire.request(.GET, "https://openapi.baidu.com/oauth/2.0/token",parameters: parameters).responseJSON { response in //print(response.result.value) let json = JSON(response.result.value!) self.bdacesstoken=json["access_token"].string! print(self.bdacesstoken) } |
调用API
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
let tmpdir=NSHomeDirectory() let recordertempfile=NSURL(fileURLWithPath: tmpdir.stringByAppendingString("/Documents/tmp.pcm")) let url="http://vop.baidu.com/server_api?lan=en&cuid=**********&token=*************" let headers = [ "Content-Type":"audio/pcm;rate=16000",//此处有坑。有分号不能用rate:16000/8000 ] Alamofire.upload(.POST, url, headers:headers,file: recordertempfile) .responseJSON { response in let json=JSON(response.result.value!) let available=(json["err_no"]).stringValue if(available=="0"){ let voicetxt=json["result"][0].string print(voicetxt) } else{ print(available) } } |