小爱音箱是小米退出的一款AI音箱,目前小米推出了小爱开放平台,供开发者使用。开始开发前,先注册小爱开放平台,个人或企业都可以注册。上一篇文章介绍了,函数计算的方式接入,下面介绍https接入自己的网站进行开发。
首先,我们看一下小爱支持的格式。
用户给小爱一个声音指令,小爱转换tts(文本),最后服务接收到的信息是一个json串,如下所示
{
“version”: “1.0”,
“query”: “播放海浪的声音”,
“session”: { // 请求的上下文信息都放这 “session_id”: “xxxxxxxxxxxxx”,
“application”: {
“app_id”: “123”
},
“user”: {
“user_id”: “456”
}
},
“request”: {
“type”: 1,
“request_id”: “tttttttttt”,
“timestamp”: 452453534523,
“locale”: “zh-CN”
}}
服务可以做如下应答,
{
“version”: “1.0”, // (string required)
“response”: { // (jsobject required)
“open_mic”: false, // (Boolean optional)
“directives”: [
{
“type”: “audio”, //(string required)
“audio_item”: { // (object optional)
“stream”: { // (object required)
“url”: “http://hailang_voice.mp3", // (string required)
}
}
} ]}, “is_session_end”: false // (boolean required)}
完整的示例,当用户对小爱说“小爱同学,何炅”,服务应答,播放一首何炅的歌。
那么,请求
{
“version”: “0.1”,
“session”: {
“is_new”: false,
“session_id”: “332896002627345408_322e60b3-e6e1-45d6-b94f-2b573e0424ab”,
“application”: {
“app_id”: “332896002627345408”
},
“user”: {
“user_id”: “rsBfwQL3ee1rvytJ9p5mIg==”,
“is_user_login”: true
},
“attributes”: { }
},
“request”: {
“type”: 1,
“request_id”: “fa003ada6ff3475bad119d09ca67c274”,
“timestamp”: 1530975918383,
“intent”: {
“query”: “何炅”,
“score”: 0.800000011920929,
“complete”: true,
“domain”: “openplatform”,
“confidence”: 1,
“skillType”: “Custom”,
“sub_domain”: “1009700”,
“app_id”: “332896002627345408”,
“request_type”: “Intent”,
“need_fetch_token”: false,
“is_direct_wakeup”: false
},
“locale”: “zh-CN”,
“is_monitor”: true
},
“query”: “何炅”,
“context”: {
“device_id”: “0ucEOkARZeNtnDEdlgIRIw==”
}}
响应
{
“version”: “1.0”,
“response”: {
“open_mic”: false,
“directives”: [
{
“type”: “audio”,
“audio_item”: {
“stream”: {
“url”: “http://static.yf2017.top/music/%E4%BD%95%E7%82%85%20-%20%E5%8F%A6%E4%B8%80%E4%B8%AA%E8%87%AA%E5%B7%B1.mp3"
nbsp; }
}
}
]
},
“is_session_end”: false}
如果是回应文本,可以这样响应
{
“version”: “1.0”,
“response”: {
“open_mic”: false,
“to_speak”: {
“type”: 0,
“text”: “青春是首诗,让我慢慢读给你听”
}
},
“is_session_end”: false}
所以,我们的服务要处理的是一个json, 然后返回一个json。
服务端处理的代码(PHP)
public function index(){
$postStr = $GLOBALS[“HTTP_RAW_POST_DATA”];
//(“小爱数据接收:”+$postStr);
//extract post data
//
$json=json_decode($postStr,true);
$q=$json[‘query’];
//(“小爱数据接收:”+$q);
// 保存请求
/
$data[‘kv’]=$q;
$data[‘res’]=$postStr;
M(‘Aireq’)->add($data);
/
if (!empty($postStr)){
if($q!='进入金大将' &&$q!='打开金大将' ){
// 查询关键字库
// 如果找到输出
if($info){
echo $info;
}else{
// 如果没找到
echo '{"version": "1.0","response": {"open\_mic": false,"to\_speak": { "type": 0,"text": "未找到匹配的记录,试试别的吧。"}},"is\_session\_end": false}';
}
}else{
echo '{"version": "1.0","response": {"open\_mic": false,"to\_speak": { "type": 0,"text": "你已进入金大将。"}},"is\_session\_end": false}';
}
exit();
}
echo 'no post';
exit();
}