直播语音结果获取接口

接口地址

https://as-liveaudio.dun.163yun.com/v1/liveaudio/callback/results

接口描述

直播语音检测结果获取接口,获取离线处理的数据后,下次调用,不会再次返回之前获取过的离线数据。

接口请求频率

小于10s/20次,请求频率过快服务器会拒绝处理。

请求参数

该接口参数与请求公共参数一致,详细见 请求公共参数

参数名称类型是否必选最大长度描述
versionStringY4接口版本v1.0

响应结果

响应字段如下,响应通用字段已省略,详细见 响应通用字段

result 数组数据结构

参数名称类型描述
asrStatusNumber音频翻译结果,2:检测中,3:检测完成,4:检测失败
asrResultNumber音频翻译检测失败原因,1:文件下载失败,2:音频流不存在,3:解析失败,4:文件格式错误
actionNumber检测结果,0:通过,1:嫌疑,2:不通过
taskIdString唯一标识
callbackString产品调用直播语音在线检测传递的 callback 字段数据
startTimeNumber最近开始时间点,单位毫秒
endTimeNumber最近结束时间点,单位毫秒
segmentsjson数组证据信息,通过时数据为空

segments 数据结构

参数名称类型描述
labelNumber分类信息,100:色情,200:广告,300:暴恐,400:违禁,500:涉政,600:谩骂
levelNumber分类级别,1:不确定,2:确定
evidenceString命中的敏感词或者声纹检测的分值

请求示例

/*
 * @(#) LiveAudioCallbackAPIDemo.java 2019-04-11
 *
 * Copyright 2019 NetEase.com, Inc. All rights reserved.
 */

package com.netease.is.antispam.demo.audio;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.apache.http.Consts;
import org.apache.http.client.HttpClient;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.netease.is.antispam.demo.utils.HttpClient4Utils;
import com.netease.is.antispam.demo.utils.SignatureUtils;

/**
 * 调用易盾反垃圾云服务获取直播语音离线结果接口API示例
 *
 * @author maxiaofeng
 * @version 2019-04-11
 */
public class LiveAudioCallbackAPIDemo {
    /**
     * 产品密钥ID,产品标识
     */
    private final static String SECRETID = "your_secret_id";
    /**
     * 产品私有密钥,服务端生成签名信息使用,请严格保管,避免泄露
     */
    private final static String SECRETKEY = "your_secret_key";
    /**
     * 业务ID,易盾根据产品业务特点分配
     */
    private final static String BUSINESSID = "your_business_id";
    /**
     * 易盾反垃圾云服务图片在线检测接口地址
     */
    private final static String API_URL = "https://as-liveaudio.dun.163yun.com/v1/liveaudio/callback/results";
    /**
     * 实例化HttpClient,发送http请求使用,可根据需要自行调参
     */
    private static HttpClient httpClient = HttpClient4Utils.createHttpClient(100, 20, 10000, 2000, 2000);

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        Map<String, String> params = new HashMap<String, String>();
        // 1.设置公共参数
        params.put("secretId", SECRETID);
        params.put("businessId", BUSINESSID);
        params.put("version", "v1.1");
        params.put("timestamp", String.valueOf(System.currentTimeMillis()));
        params.put("nonce", String.valueOf(new Random().nextInt()));

        // 2.生成签名信息
        String signature = SignatureUtils.genSignature(SECRETKEY, params);
        params.put("signature", signature);

        // 3.发送HTTP请求,这里使用的是HttpClient工具包,产品可自行选择自己熟悉的工具包发送请求
        String response = HttpClient4Utils.sendPost(httpClient, API_URL, params, Consts.UTF_8);

        // 4.解析接口返回值
        JsonObject resultObject = new JsonParser().parse(response).getAsJsonObject();
        int code = resultObject.get("code").getAsInt();
        String msg = resultObject.get("msg").getAsString();
        if (code == 200) {
            JsonArray resultArray = resultObject.getAsJsonArray("result");
            if (resultArray.size() == 0) {
                System.out.println("暂时没有结果需要获取,请稍后重试!");
            } else {
                for (JsonElement jsonElement : resultArray) {
                    JsonObject jObject = jsonElement.getAsJsonObject();
                    String taskId = jObject.get("taskId").getAsString();
                    int asrStatus = jObject.get("asrStatus").getAsInt();
                    if (asrStatus == 4) {
                        int asrResult = jObject.get("asrResult").getAsInt();
                        System.out.println(String.format("检测失败: taskId=%s, asrResult=%s", taskId, asrResult));
                    } else {
                        int action = jObject.get("action").getAsInt();
                        JsonArray segmentArray = jObject.getAsJsonArray("segments");
                        if (action == 0) {
                            System.out.println(String.format("taskId=%s,结果:通过,证据信息如下:%s", taskId, segmentArray.toString()));
                        } else if (action == 1 || action == 2) {
                            // for (JsonElement labelElement : segmentArray) {
                            // 	JsonObject lObject = labelElement.getAsJsonObject();
                            // 	int label = lObject.get("label").getAsInt();
                            // 	int level = lObject.get("level").getAsInt();
                            // }
                            System.out.println(String.format("taskId=%s,结果:%s,证据信息如下:%s", taskId, action == 1 ? "不确定" : "不通过",
                                    segmentArray.toString()));
                        }
                    }
                }
            }
        } else {
            System.out.println(String.format("ERROR: code=%s, msg=%s", code, msg));
        }
    }

}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""易
盾直播音频结果获取接口python示例代码
接口文档: http://dun.163.com/api.html
python版本:python3.7
运行:
    1. 修改 SECRET_ID,SECRET_KEY,BUSINESS_ID 为对应申请到的值
    2. $ python liveaudio_callback.py
"""
__author__ = 'yidun-dev'
__date__ = '2019/11/27'
__version__ = '0.2-dev'

import hashlib
import time
import random
import urllib.request as urlrequest
import urllib.parse as urlparse
import json


class LiveAudioCallbackAPIDemo(object):
    """直播音频检测结果获取接口示例代码"""

    API_URL = "https://as-liveaudio.dun.163yun.com/v1/liveaudio/callback/results"
    VERSION = "v1.1"

    def __init__(self, secret_id, secret_key, business_id):
        """
        Args:
            secret_id (str) 产品密钥ID,产品标识
            secret_key (str) 产品私有密钥,服务端生成签名信息使用
            business_id (str) 业务ID,易盾根据产品业务特点分配
        """
        self.secret_id = secret_id
        self.secret_key = secret_key
        self.business_id = business_id

    def gen_signature(self, params=None):
        """生成签名信息
        Args:
            params (object) 请求参数
        Returns:
            参数签名md5值
        """
        buff = ""
        for k in sorted(params.keys()):
            buff += str(k) + str(params[k])
        buff += self.secret_key
        return hashlib.md5(buff.encode("utf8")).hexdigest()

    def check(self):
        """请求易盾接口
        Returns:
            请求结果,json格式
        """
        params = {}
        params["secretId"] = self.secret_id
        params["businessId"] = self.business_id
        params["version"] = self.VERSION
        params["timestamp"] = int(time.time() * 1000)
        params["nonce"] = int(random.random()*100000000)
        params["signature"] = self.gen_signature(params)

        try:
            params = urlparse.urlencode(params).encode("utf8")
            request = urlrequest.Request(self.API_URL, params)
            content = urlrequest.urlopen(request, timeout=10).read()
            return json.loads(content)
        except Exception as ex:
            print("调用API接口失败:", str(ex))


if __name__ == "__main__":
    """示例代码入口"""
    SECRET_ID = "your_secret_id"  # 产品密钥ID,产品标识
    SECRET_KEY = "your_secret_key"  # 产品私有密钥,服务端生成签名信息使用,请严格保管,避免泄露
    BUSINESS_ID = "your_business_id"  # 业务ID,易盾根据产品业务特点分配
    api = LiveAudioCallbackAPIDemo(SECRET_ID, SECRET_KEY, BUSINESS_ID)
    
    ret = api.check()

    code: int = ret["code"]
    msg: str = ret["msg"]
    if code == 200:
        resultArray: list = ret["result"]
        if len(resultArray) == 0:
            print("暂时没有结果需要获取, 请稍后重试!")
        else:
            for result in resultArray:
                taskId: str = result["taskId"]
                asrStatus: int = result["asrStatus"]
                if asrStatus == 4:
                    asrResult: int = result["asrResult"]
                    print("检测失败: taskId=%s, asrResult=%s" % (taskId, asrResult))
                else:
                    action: int = result["action"]
                    segmentArray: list = result["labels"]
                    if action == 0:
                        print("taskId=%s, 结果: 通过, 证据信息如下: %s" % (taskId, segmentArray))
                    elif action == 1 or action == 2:
                        # for segmentItem in segmentArray:
                        #     label: int = segmentItem["label"]
                        #     level: int = segmentItem["level"]
                        print("taskId=%s, 结果: %s,证据信息如下: %s" % (taskId, "不确定" if action == 1 else "不通过", segmentArray))
    else:
        print("ERROR: code=%s, msg=%s" % (ret["code"], ret["msg"]))
<?php
/** 离线直播音频检查结果查询接口 */
/** 产品密钥ID,产品标识 */
define("SECRETID", "your_secret_id");
/** 产品私有密钥,服务端生成签名信息使用,请严格保管,避免泄露 */
define("SECRETKEY", "your_secret_key");
/** 业务ID,易盾根据产品业务特点分配 */
define("BUSINESSID", "your_business_id");
/** 易盾反垃圾云服务音频检测结果获取接口地址 */
define("API_URL", "https://as-liveaudio.dun.163yun.com/v1/liveaudio/callback/results");
/** api version */
define("VERSION", "v1.1");
/** API timeout*/
define("API_TIMEOUT", 10);
/** php内部使用的字符串编码 */
define("INTERNAL_STRING_CHARSET", "auto");
/**
 * 计算参数签名
 * $params 请求参数
 * $secretKey secretKey
 */
function gen_signature($secretKey, $params){
	ksort($params);
	$buff="";
	foreach($params as $key=>$value){
	     if($value !== null) {
	        $buff .=$key;
		$buff .=$value;
    	     }
	}
	$buff .= $secretKey;
	return md5($buff);
}
/**
 * 将输入数据的编码统一转换成utf8
 * @params 输入的参数
 */
function toUtf8($params){
	$utf8s = array();
    foreach ($params as $key => $value) {
    	$utf8s[$key] = is_string($value) ? mb_convert_encoding($value, "utf8", INTERNAL_STRING_CHARSET) : $value;
    }
    return $utf8s;
}
/**
 * 反垃圾请求接口简单封装
 * $params 请求参数
 */
function check(){
    $params = array();
	$params["secretId"] = SECRETID;
	$params["businessId"] = BUSINESSID;
	$params["version"] = VERSION;
	$params["timestamp"] = time() * 1000;// time in milliseconds
	$params["nonce"] = sprintf("%d", rand()); // random int
	$params = toUtf8($params);
	$params["signature"] = gen_signature(SECRETKEY, $params);
	// var_dump($params);
	$options = array(
	    'http' => array(
	        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
	        'method'  => 'POST',
	        'timeout' => API_TIMEOUT, // read timeout in seconds
	        'content' => http_build_query($params),
	    ),
	);
	// var_dump($params);
	$context  = stream_context_create($options);
	$result = file_get_contents(API_URL, false, $context);
	// var_dump($result);
	if($result === FALSE){
		return array("code"=>500, "msg"=>"file_get_contents failed.");
	}else{
		return json_decode($result, true);	
	}
}
// 简单测试
function main(){
    echo "mb_internal_encoding=".mb_internal_encoding()."\n";
	$ret = check();
	var_dump($ret);
	if ($ret["code"] == 200) {
		$result_array = $ret["result"];
		foreach($result_array as $res_index => $result){
		    $taskId = $result["taskId"];
			$action = $result["action"];
            $segment_array = $result["segments"];
            // 证据信息如下
            /*foreach($segment_array as $label_index => $segmentsInfo){
                $label = $segmentsInfo["label"];
                $level = $segmentsInfo["level"];
            }*/
            if ($action == 0) {
                echo "结果:通过,taskId=".$taskId;
            } else if ($action == 2) {
                echo "结果:不通过,taskId=".$taskId;
            }
		}
    }else{
    	var_dump($ret);
    }
}
main();
?>
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net.Http;

namespace Com.Netease.Is.Antispam.Demo
{
    class LiveAudioCallbackApiDemo
    {
        public static void audioCallBack()
        {
            /** 产品密钥ID,产品标识 */
            String secretId = "your_secret_id";
            /** 产品私有密钥,服务端生成签名信息使用,请严格保管,避免泄露 */
            String secretKey = "your_secret_key";
            /** 业务ID,易盾根据产品业务特点分配 */
            String businessId = "your_business_id";
            /** 易盾反垃圾云服务直播音频离线结果获取接口地址 */
            String apiUrl = "https://as-liveaudio.dun.163yun.com/v1/liveaudio/callback/results";
            Dictionary<String, String> parameters = new Dictionary<String, String>();

            long curr = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
            String time = curr.ToString();

            // 1.设置公共参数
            parameters.Add("secretId", secretId);
            parameters.Add("businessId", businessId);
            parameters.Add("version", "v1.1");
            parameters.Add("timestamp", time);
            parameters.Add("nonce", new Random().Next().ToString());

            // 2.生成签名信息
            String signature = Utils.genSignature(secretKey, parameters);
            parameters.Add("signature", signature);

            // 3.发送HTTP请求
            HttpClient client = Utils.makeHttpClient();
            String result = Utils.doPost(client, apiUrl, parameters, 10000);
            if(result != null)
            {
                JObject ret = JObject.Parse(result);
                int code = ret.GetValue("code").ToObject<Int32>();
                String msg = ret.GetValue("msg").ToObject<String>();
                if (code == 200)
                {
                    JArray array = (JArray)ret.SelectToken("result");
                    foreach (var item in array)
                    {
                        JObject jObject = (JObject)item;
                        int asrStatus = jObject.GetValue("asrStatus").ToObject<Int32>();
                        String taskId = jObject.GetValue("taskId").ToObject<String>();
                        if (asrStatus == 4)
                        {
                            int asrResult = jObject.GetValue("asrResult").ToObject<Int32>();
                            Console.WriteLine(String.Format("检测失败: taskId={0}, asrResult={1}", taskId, asrResult));
                        }
                        else
                        {
                            int action = jObject.GetValue("action").ToObject<Int32>();
                            // 证据信息
                            JArray segmentArray = (JArray)jObject.SelectToken("segments");
                            if (action == 0) {
                                Console.WriteLine(String.Format("结果:通过!taskId={0}", taskId));
                            } else if (action == 1 || action == 2) {
                                Console.WriteLine(String.format("taskId={0},结果:{1}", taskId, action == 1 ? "不确定" : "不通过"));
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine(String.Format("ERROR: code={0}, msg={1}", code, msg));
                }
            }
            else
            {
                Console.WriteLine("Request failed!");
            }
        }
    }
}	
var utils=require("./utils");
//产品密钥ID,产品标识 
var secretId="your_secret_id";
// 产品私有密钥,服务端生成签名信息使用,请严格保管,避免泄露 
var secretKey="your_secret_key";
// 业务ID,易盾根据产品业务特点分配 
var businessId="your_business_id";
// 易盾反垃圾云服务直播音频离线结果获取接口地址
var apiurl="https://as-liveaudio.dun.163yun.com/v1/liveaudio/callback/results";

//请求参数
var post_data = {
	// 1.设置公有有参数
	secretId:secretId,
	businessId:businessId,
	version:"v1",
	timestamp:new Date().getTime(),
	nonce:utils.noncer()
};
var signature=utils.genSignature(secretKey,post_data);
post_data.signature=signature;
//http请求结果
var responseCallback=function(responseData){
	console.log(responseData);
	var data = JSON.parse(responseData);
	var code=data.code;
	var msg=data.msg;
	if(code==200){
        var result=data.result;
        if(result.length==0){
            console.log("暂时没有结果需要获取,请稍后重试!");
        }else{
            for(var i=0;i<result.length;i++){
                var obj=result[i];
                var taskId = obj.taskId;
                var asrStatus = obj.asrStatus;
                if(asrStatus==4){
                    var asrResult = obj.asrResult;
                    console.log("检测失败:taskId="+taskId+",asrResult="+asrResult);
                }else{
                    var action = obj.action;
                    var segments = obj.segments;
                    if(action==0){
                        console.log("通过:taskId="+taskId);
                    }else if(action==1||action==2){
                        /*for(var j=0;j<segments.length;j++){
                    		var segment=segments[j];
                    		var label=segment.label;
                    		var level=segment.level;
                		}*/
                        console.log("结果:"+action==1?"不确定":"不通过"+"!taskId="+taskId);
                    }
                }
            }
        }
	}else{
		 console.log('ERROR:code=' + code+',msg='+msg);
	}
}
utils.sendHttpRequest(apiurl,"POST",post_data,responseCallback);

响应示例

当获取到离线结果时,输出示例如下:

{
	"code": 200,
	"msg": "ok",
	"result": [{
            "taskId":"50992f04-563f-4976-b8c7-bf78aa65d9f4",
            "action":2,
            "asrStatus":3, 
            "asrResult":0,
            "callback":"",
            "startTime":20,
            "endTime":30,
            "segments": [
                 {
                    "label":500,
                    "level":2,
                    "evidence":"特朗普"
                }
            ]
           },{
            "taskId":"50992f04-563f-4976-b8c7-bf78aa65d9f4",
            "action":2,
            "asrStatus":3, 
            "asrResult":0,
            "callback":"",
            "startTime":40,
            "endTime":50,
            "segments": [
                 {
                    "label":100,
                    "level":2,
                    "evidence":"裸聊"
                }
            ]
           }]
}

当无最新离线结果需要获取时,输出示例如下:

{
    "code": 200,
    "msg": "ok",
    "result":[]
}
Online Chat Tel:95163223