O Voice Moderation 2.0 oferece dois métodos de integração: SDK e HTTPS nativo. Recomendamos o uso do SDK, pois ele gerencia automaticamente a verificação de assinatura e a construção do corpo da requisição.
Regiões suportadas
|
Região |
Endpoint público |
Endpoint VPC |
Códigos de serviço suportados |
|
China (Shanghai) |
green-cip.cn-shanghai.aliyuncs.com |
green-cip-vpc.cn-shanghai.aliyuncs.com |
|
|
China (Shenzhen) |
green-cip.cn-shenzhen.aliyuncs.com |
green-cip-vpc.cn-shenzhen.aliyuncs.com |
|
|
China (Hangzhou) |
green-cip.cn-hangzhou.aliyuncs.com |
green-cip-vpc.cn-hangzhou.aliyuncs.com |
|
|
China (Beijing) |
green-cip.cn-beijing.aliyuncs.com |
green-cip-vpc.cn-beijing.aliyuncs.com |
|
|
Singapore |
|
|
|
|
US (Virginia) |
|
|
|
Ao definir o parâmetro service na requisição VoiceModeration, utilize um código de serviço compatível com a região selecionada. O uso de um código não suportado resultará em erro.
Linguagens de SDK suportadas
Java 1.8 ou superior
Python 3.6 ou superior
PHP 5.6 ou superior
Go
C#
Funcionamento
O Voice Moderation 2.0 adota um padrão assíncrono de envio e consulta:
Envie uma tarefa de moderação com
VoiceModeration. A API retorna umtaskId.Enviar uma tarefa de moderação de vozConsulte os resultados com
VoiceModerationResult, informando otaskId.Analise o resultado — verifique
riskLevelesliceDetailspara determinar o desfecho da moderação.
Para arquivos de áudio locais sem URL pública, faça primeiro o upload do arquivo para um bucket OSS do Content Moderation usando um token temporário obtido via DescribeUploadToken. Em seguida, envie a tarefa de moderação utilizando o caminho do objeto no OSS.
Pré-requisitos
Antes de começar, certifique-se de ter:
Ativado o serviço Voice Moderation 2.0. O método de faturamento padrão é pagamento conforme o uso. A cobrança ocorre diariamente, com base no consumo real. Se você não utilizar o serviço, nenhuma taxa será gerada.
Um usuário do Resource Access Management (RAM) com a política de sistema
AliyunYundunGreenWebFullAccessconcedida. Consulte Criar um usuário RAM e Conceder permissões a um usuário RAM.Um par de AccessKey para o usuário RAM. Consulte Criar um par de AccessKey.
As variáveis de ambiente
ALIBABA_CLOUD_ACCESS_KEY_IDeALIBABA_CLOUD_ACCESS_KEY_SECRETconfiguradas com o AccessKey ID e o AccessKey secret do seu usuário RAM.
Os SDKs da Alibaba Cloud criam credenciais padrão ao ler as variáveis de ambiente ALIBABA_CLOUD_ACCESS_KEY_ID e ALIBABA_CLOUD_ACCESS_KEY_SECRET. Ao chamar uma operação de API, o programa lê seu AccessKey dessas variáveis e conclui a autenticação automaticamente. Antes de executar os códigos de exemplo do SDK, configure as variáveis de ambiente. Para mais informações, consulte Configurar credenciais de autenticação.
Java SDK
Código-fonte: GitHub | Maven Central
O SDK oferece suporte a três cenários de moderação de áudio. Todos os exemplos utilizam VoiceModeration para enviar uma tarefa e VoiceModerationResult para recuperar o resultado.
Detectar áudio acessível publicamente
Utilize este cenário quando o arquivo de áudio estiver acessível por meio de uma URL pública.
Instalar a dependência
Adicione o seguinte trecho ao seu arquivo Maven pom.xml:
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>green20220302</artifactId>
<version>3.3.3</version>
</dependency>
Enviar uma tarefa de moderação
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.VoiceModerationResultRequest;
import com.aliyun.green20220302.models.VoiceModerationResultResponse;
import com.aliyun.green20220302.models.VoiceModerationResultResponseBody;
import com.aliyun.teaopenapi.models.Config;
public class VoiceModerationResultDemo {
public static void main(String[] args) throws Exception {
Config config = new Config();
/**
* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
* Common methods to obtain environment variables:
* Method 1:
* Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
* Method 2:
* Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
config.setAccessKeyId("We recommend that you obtain the AccessKey ID of your RAM user from an environment variable");
config.setAccessKeySecret("We recommend that you obtain the AccessKey secret of your RAM user from an environment variable");
// Modify the region and endpoint as needed.
config.setRegionId("ap-southeast-1");
config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com");
// Connection timeout period in milliseconds (ms).
config.setReadTimeout(6000);
// Read timeout period in milliseconds (ms).
config.setConnectTimeout(3000);
// Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
Client client = new Client(config);
JSONObject serviceParameters = new JSONObject();
// The taskId returned when the task was submitted.
serviceParameters.put("taskId", "The task ID returned for the moderation task.");
VoiceModerationResultRequest voiceModerationResultRequest = new VoiceModerationResultRequest();
// Moderation type: audio_multilingual_global for multi-language audio moderation.
voiceModerationResultRequest.setService("audio_multilingual_global");
voiceModerationResultRequest.setServiceParameters(serviceParameters.toJSONString());
try {
VoiceModerationResultResponse response = client.voiceModerationResult(voiceModerationResultRequest);
if (response.getStatusCode() == 200) {
VoiceModerationResultResponseBody result = response.getBody();
System.out.println("requestId=" + result.getRequestId());
System.out.println("code=" + result.getCode());
System.out.println("msg=" + result.getMessage());
if (200 == result.getCode()) {
VoiceModerationResultResponseBody.VoiceModerationResultResponseBodyData data = result.getData();
System.out.println("sliceDetails = " + JSON.toJSONString(data.getSliceDetails()));
System.out.println("taskId = " + data.getTaskId());
System.out.println("url = " + data.getUrl());
System.out.println("riskLevel = " + data.getRiskLevel());
} else {
System.out.println("voice moderation result not success. code:" + result.getCode());
}
} else {
System.out.println("response not success. status:" + response.getStatusCode());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.VoiceModerationRequest;
import com.aliyun.green20220302.models.VoiceModerationResponse;
import com.aliyun.green20220302.models.VoiceModerationResponseBody;
import com.aliyun.teaopenapi.models.Config;
public class OssVoiceModerationDemo {
public static void main(String[] args) throws Exception {
Config config = new Config();
/**
* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
* Common methods to obtain environment variables:
* Method 1:
* Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
* Method 2:
* Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
config.setAccessKeyId("We recommend that you obtain the AccessKey ID of your RAM user from an environment variable");
config.setAccessKeySecret("We recommend that you obtain the AccessKey secret of your RAM user from an environment variable");
// Modify the region and endpoint as needed.
config.setRegionId("ap-southeast-1");
config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com");
// Connection timeout period in milliseconds (ms).
config.setReadTimeout(6000);
// Read timeout period in milliseconds (ms).
config.setConnectTimeout(3000);
// Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
Client client = new Client(config);
JSONObject serviceParameters = new JSONObject();
serviceParameters.put("ossBucketName", "bucket_01");
serviceParameters.put("ossObjectName", "test/test.flv");
serviceParameters.put("ossRegionId", "ap-southeast-1");
VoiceModerationRequest voiceModerationRequest = new VoiceModerationRequest();
// Moderation type. audio_media_detection indicates audio file moderation, and live_stream_detection indicates audio live stream moderation.
voiceModerationRequest.setService("audio_media_detection");
voiceModerationRequest.setServiceParameters(serviceParameters.toJSONString());
try {
VoiceModerationResponse response = client.voiceModeration(voiceModerationRequest);
if (response.getStatusCode() == 200) {
VoiceModerationResponseBody result = response.getBody();
System.out.println(JSON.toJSONString(result));
System.out.println("requestId = " + result.getRequestId());
System.out.println("code = " + result.getCode());
System.out.println("msg = " + result.getMessage());
Integer code = result.getCode();
if (200 == code) {
VoiceModerationResponseBody.VoiceModerationResponseBodyData data = result.getData();
System.out.println("taskId = [" + data.getTaskId() + "]");
} else {
System.out.println("voice moderation not success. code:" + code);
}
} else {
System.out.println("response not success. status:" + response.getStatusCode());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.VoiceModerationResultRequest;
import com.aliyun.green20220302.models.VoiceModerationResultResponse;
import com.aliyun.green20220302.models.VoiceModerationResultResponseBody;
import com.aliyun.teaopenapi.models.Config;
public class VoiceModerationResultDemo {
public static void main(String[] args) throws Exception {
Config config = new Config();
/**
* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
* Common methods to obtain environment variables:
* Method 1:
* Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
* Method 2:
* Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
config.setAccessKeyId("We recommend that you obtain the AccessKey ID of your RAM user from an environment variable");
config.setAccessKeySecret("We recommend that you obtain the AccessKey secret of your RAM user from an environment variable");
// Modify the region and endpoint as needed.
config.setRegionId("ap-southeast-1");
config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com");
// Connection timeout period in milliseconds (ms).
config.setReadTimeout(6000);
// Read timeout period in milliseconds (ms).
config.setConnectTimeout(3000);
// Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
Client client = new Client(config);
JSONObject serviceParameters = new JSONObject();
// The taskId returned when the task was submitted.
serviceParameters.put("taskId", "The task ID returned for the moderation task.");
VoiceModerationResultRequest voiceModerationResultRequest = new VoiceModerationResultRequest();
// Moderation type: audio_multilingual_global for multi-language audio moderation.
voiceModerationResultRequest.setService("audio_multilingual_global");
voiceModerationResultRequest.setServiceParameters(serviceParameters.toJSONString());
try {
VoiceModerationResultResponse response = client.voiceModerationResult(voiceModerationResultRequest);
if (response.getStatusCode() == 200) {
VoiceModerationResultResponseBody result = response.getBody();
System.out.println("requestId=" + result.getRequestId());
System.out.println("code=" + result.getCode());
System.out.println("msg=" + result.getMessage());
if (200 == result.getCode()) {
VoiceModerationResultResponseBody.VoiceModerationResultResponseBodyData data = result.getData();
System.out.println("sliceDetails = " + JSON.toJSONString(data.getSliceDetails()));
System.out.println("taskId = " + data.getTaskId());
System.out.println("url = " + data.getUrl());
System.out.println("riskLevel = " + data.getRiskLevel());
} else {
System.out.println("voice moderation result not success. code:" + result.getCode());
}
} else {
System.out.println("response not success. status:" + response.getStatusCode());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
import com.alibaba.fastjson.JSON;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.DescribeUploadTokenResponse;
import com.aliyun.green20220302.models.DescribeUploadTokenResponseBody;
import com.aliyun.green20220302.models.VoiceModerationRequest;
import com.aliyun.green20220302.models.VoiceModerationResponse;
import com.aliyun.green20220302.models.VoiceModerationResponseBody;
import com.aliyun.green20220302.models.VoiceModerationResponseBody.VoiceModerationResponseBodyData;
import com.aliyun.green20220302.models.VoiceModerationResponseBody.VoiceModerationResponseBodyDataResult;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
public class LocalVoiceModerationDemo {
/**Specifies whether the service is deployed in a VPC.*/
public static boolean isVPC = false;
/**The token used to upload the file. The key is the endpoint and the value is the token.*/
public static Map<String, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData> tokenMap = new HashMap<>();
/**The client used to upload the file.*/
public static OSS ossClient = null;
/**
* Create a client.
*
* @param accessKeyId
* @param accessKeySecret
* @param endpoint
* @return
* @throws Exception
*/
public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
Config config = new Config();
config.setAccessKeyId(accessKeyId);
config.setAccessKeySecret(accessKeySecret);
// Modify the endpoint as needed.
config.setEndpoint(endpoint);
return new Client(config);
}
/**
* Create a client to upload a file.
*
* @param tokenData
* @param isVPC
*/
public static void getOssClient(DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData, boolean isVPC) {
//Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
if (isVPC) {
ossClient = new OSSClientBuilder().build(tokenData.ossInternalEndPoint, tokenData.getAccessKeyId(), tokenData.getAccessKeySecret(), tokenData.getSecurityToken());
} else {
ossClient = new OSSClientBuilder().build(tokenData.ossInternetEndPoint, tokenData.getAccessKeyId(), tokenData.getAccessKeySecret(), tokenData.getSecurityToken());
}
}
/**
* Upload a file.
*
* @param filePath
* @param tokenData
* @return
* @throws Exception
*/
public static String uploadFile(String filePath, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData) throws Exception {
String[] split = filePath.split("\\.");
String objectName;
if (split.length > 1) {
objectName = tokenData.getFileNamePrefix() + UUID.randomUUID() + "." + split[split.length - 1];
} else {
objectName = tokenData.getFileNamePrefix() + UUID.randomUUID();
}
PutObjectRequest putObjectRequest = new PutObjectRequest(tokenData.getBucketName(), objectName, new File(filePath));
ossClient.putObject(putObjectRequest);
return objectName;
}
public static VoiceModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
//Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
Client client = createClient(accessKeyId, accessKeySecret, endpoint);
RuntimeOptions runtime = new RuntimeOptions();
//The full path of the local file. Example: D:/localPath/exampleFile.mp3.
String filePath = "D:/localPath/exampleFile.mp3";
//Obtain a temporary token to upload the file.
if (tokenMap.get(endpoint) == null || tokenMap.get(endpoint).expiration <= System.currentTimeMillis() / 1000) {
DescribeUploadTokenResponse tokenResponse = client.describeUploadToken();
tokenMap.put(endpoint, tokenResponse.getBody().getData());
}
//Create a client to upload the file.
getOssClient(tokenMap.get(endpoint), isVPC);
//Upload the file.
String objectName = uploadFile(filePath, tokenMap.get(endpoint));
// Construct moderation parameters.
Map<String, String> serviceParameters = new HashMap<>();
//The information about the file upload.
serviceParameters.put("ossBucketName", tokenMap.get(endpoint).getBucketName());
serviceParameters.put("ossObjectName", objectName);
serviceParameters.put("dataId", UUID.randomUUID().toString());
VoiceModerationRequest request = new VoiceModerationRequest();
// Moderation type. audio_media_detection indicates audio file moderation.
request.setService("audio_multilingual_global");
request.setServiceParameters(JSON.toJSONString(serviceParameters));
VoiceModerationResponse response = null;
try {
response = client.voiceModerationWithOptions(request, runtime);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
public static void main(String[] args) throws Exception {
/**
* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
* Common methods to obtain environment variables:
* Method 1:
* Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
* Method 2:
* Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
String accessKeyId = "We recommend that you obtain the AccessKey ID of your RAM user from an environment variable";
String accessKeySecret = "We recommend that you obtain the AccessKey secret of your RAM user from an environment variable";
// Modify the region and endpoint as needed.
VoiceModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.ap-southeast-1.aliyuncs.com");
try {
// Print the moderation result.
if (response != null) {
if (response.getStatusCode() == 200) {
VoiceModerationResponseBody body = response.getBody();
System.out.println(JSON.toJSONString(body));
System.out.println("requestId = " + body.getRequestId());
System.out.println("code = " + body.getCode());
System.out.println("msg = " + body.getMessage());
Integer code = body.getCode();
if (200 == code) {
VoiceModerationResponseBody.VoiceModerationResponseBodyData data = body.getData();
System.out.println("taskId = [" + data.getTaskId() + "]");
} else {
System.out.println("voice moderation not success. code:" + code);
}
} else {
System.out.println("response not success. status:" + response.getStatusCode());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.VoiceModerationResultRequest;
import com.aliyun.green20220302.models.VoiceModerationResultResponse;
import com.aliyun.green20220302.models.VoiceModerationResultResponseBody;
import com.aliyun.teaopenapi.models.Config;
public class VoiceModerationResultDemo {
public static void main(String[] args) throws Exception {
Config config = new Config();
/**
* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
* Common methods to obtain environment variables:
* Method 1:
* Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
* Method 2:
* Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
config.setAccessKeyId("We recommend that you obtain the AccessKey ID of your RAM user from an environment variable");
config.setAccessKeySecret("We recommend that you obtain the AccessKey secret of your RAM user from an environment variable");
// Modify the region and endpoint as needed.
config.setRegionId("ap-southeast-1");
config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com");
// Connection timeout period in milliseconds (ms).
config.setReadTimeout(6000);
// Read timeout period in milliseconds (ms).
config.setConnectTimeout(3000);
// Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
Client client = new Client(config);
JSONObject serviceParameters = new JSONObject();
// The taskId returned when the task was submitted.
serviceParameters.put("taskId", "The task ID returned for the moderation task.");
VoiceModerationResultRequest voiceModerationResultRequest = new VoiceModerationResultRequest();
// Moderation type: audio_multilingual_global for multi-language audio moderation.
voiceModerationResultRequest.setService("audio_multilingual_global");
voiceModerationResultRequest.setServiceParameters(serviceParameters.toJSONString());
try {
VoiceModerationResultResponse response = client.voiceModerationResult(voiceModerationResultRequest);
if (response.getStatusCode() == 200) {
VoiceModerationResultResponseBody result = response.getBody();
System.out.println("requestId=" + result.getRequestId());
System.out.println("code=" + result.getCode());
System.out.println("msg=" + result.getMessage());
if (200 == result.getCode()) {
VoiceModerationResultResponseBody.VoiceModerationResultResponseBodyData data = result.getData();
System.out.println("sliceDetails = " + JSON.toJSONString(data.getSliceDetails()));
System.out.println("taskId = " + data.getTaskId());
System.out.println("url = " + data.getUrl());
} else {
System.out.println("voice moderation result not success. code:" + result.getCode());
}
} else {
System.out.println("response not success. status:" + response.getStatusCode());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Recuperar o resultado da moderaçãoRecuperar resultado da moderação de voz
Cancelar uma tarefa de detecção de transmissão ao vivo
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.VoiceModerationCancelRequest;
import com.aliyun.green20220302.models.VoiceModerationCancelResponse;
import com.aliyun.green20220302.models.VoiceModerationCancelResponseBody;
import com.aliyun.teaopenapi.models.Config;
public class VoiceModerationCancelDemo {
public static void main(String[] args) throws Exception {
Config config = new Config();
/**
* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
* Common methods to obtain environment variables:
* Method 1:
* Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
* Method 2:
* Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
config.setAccessKeyId("We recommend that you obtain the AccessKey ID of your RAM user from an environment variable");
config.setAccessKeySecret("We recommend that you obtain the AccessKey secret of your RAM user from an environment variable");
// Modify the region and endpoint as needed.
config.setRegionId("cn-shanghai");
config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
// Connection timeout period in milliseconds (ms).
config.setReadTimeout(6000);
// Read timeout period in milliseconds (ms).
config.setConnectTimeout(3000);
// Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
Client client = new Client(config);
JSONObject serviceParameters = new JSONObject();
// The taskId returned when the task was submitted.
serviceParameters.put("taskId", "The task ID returned for the moderation task.");
VoiceModerationCancelRequest voiceModerationCancelRequest = new VoiceModerationCancelRequest();
// Moderation type. audio_media_detection indicates audio file moderation, and live_stream_detection indicates audio live stream moderation.
voiceModerationCancelRequest.setService("live_stream_detection");
voiceModerationCancelRequest.setServiceParameters(serviceParameters.toJSONString());
try {
VoiceModerationCancelResponse response = client.voiceModerationCancel(voiceModerationCancelRequest);
if (response.getStatusCode() == 200) {
VoiceModerationCancelResponseBody result = response.getBody();
System.out.println("requestId=" + result.getRequestId());
System.out.println("code=" + result.getCode());
System.out.println("msg=" + result.getMessage());
if (200 != result.getCode()) {
System.out.println("voice moderation cancel not success. code:" + result.getCode());
}
} else {
System.out.println("response not success. status:" + response.getStatusCode());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.VoiceModerationResultRequest;
import com.aliyun.green20220302.models.VoiceModerationResultResponse;
import com.aliyun.green20220302.models.VoiceModerationResultResponseBody;
import com.aliyun.teaopenapi.models.Config;
public class VoiceModerationResultDemo {
public static void main(String[] args) throws Exception {
Config config = new Config();
config.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
config.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.setRegionId("ap-southeast-1");
config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com");
config.setReadTimeout(6000);
config.setConnectTimeout(3000);
Client client = new Client(config);
JSONObject serviceParameters = new JSONObject();
serviceParameters.put("taskId", "<task-id>");
VoiceModerationResultRequest request = new VoiceModerationResultRequest();
request.setService("audio_multilingual_global");
request.setServiceParameters(serviceParameters.toJSONString());
try {
VoiceModerationResultResponse response = client.voiceModerationResult(request);
if (response.getStatusCode() == 200) {
VoiceModerationResultResponseBody result = response.getBody();
if (200 == result.getCode()) {
VoiceModerationResultResponseBody.VoiceModerationResultResponseBodyData data = result.getData();
System.out.println("taskId: " + data.getTaskId());
System.out.println("riskLevel: " + data.getRiskLevel());
System.out.println("url: " + data.getUrl());
System.out.println("sliceDetails: " + JSON.toJSONString(data.getSliceDetails()));
} else {
System.out.println("Failed to get result. code: " + result.getCode());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Detectar áudio local
Escolha este cenário quando o arquivo de áudio estiver em uma máquina local, sem uma URL pública. O SDK primeiro faz o upload do arquivo para um bucket do Object Storage Service de moderação de conteúdo usando um token temporário e, em seguida, envia a tarefa de moderação utilizando o caminho do objeto no OSS.
Instalar as dependências
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>green20220302</artifactId>
<version>3.3.3</version>
</dependency>
Enviar uma tarefa de moderação
Para recuperar os resultados, utilize o mesmo exemplo VoiceModerationResultDemo descrito em Detectar áudio acessível publicamente.
Cancelar uma tarefa de detecção de transmissão ao vivo
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.VoiceModerationCancelRequest;
import com.aliyun.green20220302.models.VoiceModerationCancelResponse;
import com.aliyun.green20220302.models.VoiceModerationCancelResponseBody;
import com.aliyun.teaopenapi.models.Config;
public class VoiceModerationCancelDemo {
public static void main(String[] args) throws Exception {
Config config = new Config();
/**
* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
* Common methods to obtain environment variables:
* Method 1:
* Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
* Method 2:
* Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
config.setAccessKeyId("We recommend that you obtain the AccessKey ID of your RAM user from an environment variable");
config.setAccessKeySecret("We recommend that you obtain the AccessKey secret of your RAM user from an environment variable");
// Modify the region and endpoint as needed.
config.setRegionId("cn-shanghai");
config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
// Connection timeout period in milliseconds (ms).
config.setReadTimeout(6000);
// Read timeout period in milliseconds (ms).
config.setConnectTimeout(3000);
// Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
Client client = new Client(config);
JSONObject serviceParameters = new JSONObject();
// The taskId returned when the task was submitted.
serviceParameters.put("taskId", "The task ID returned for the moderation task.");
VoiceModerationCancelRequest voiceModerationCancelRequest = new VoiceModerationCancelRequest();
// Moderation type. audio_media_detection indicates audio file moderation, and live_stream_detection indicates audio live stream moderation.
voiceModerationCancelRequest.setService("live_stream_detection");
voiceModerationCancelRequest.setServiceParameters(serviceParameters.toJSONString());
try {
VoiceModerationCancelResponse response = client.voiceModerationCancel(voiceModerationCancelRequest);
if (response.getStatusCode() == 200) {
VoiceModerationCancelResponseBody result = response.getBody();
System.out.println("requestId=" + result.getRequestId());
System.out.println("code=" + result.getCode());
System.out.println("msg=" + result.getMessage());
if (200 != result.getCode()) {
System.out.println("voice moderation cancel not success. code:" + result.getCode());
}
} else {
System.out.println("response not success. status:" + response.getStatusCode());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Detectar áudio armazenado no OSS
Aplique este cenário quando os arquivos de áudio já estiverem em um bucket do Object Storage Service (OSS) da Alibaba Cloud. Conceda acesso ao serviço de Moderação de Conteúdo para o seu bucket do OSS criando uma função de serviço na página de Autorização de Acesso a Recursos da Nuvem.
Instalar a dependência
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>green20220302</artifactId>
<version>3.3.3</version>
</dependency>
Enviar uma tarefa de moderação
Para recuperar os resultados, utilize o mesmo exemplo VoiceModerationResultDemo descrito em Detectar áudio acessível publicamente.
Cancelar uma tarefa de detecção de transmissão ao vivo
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.VoiceModerationCancelRequest;
import com.aliyun.green20220302.models.VoiceModerationCancelResponse;
import com.aliyun.green20220302.models.VoiceModerationCancelResponseBody;
import com.aliyun.teaopenapi.models.Config;
public class VoiceModerationCancelDemo {
public static void main(String[] args) throws Exception {
Config config = new Config();
/**
* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
* Common methods to obtain environment variables:
* Method 1:
* Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
* Method 2:
* Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
config.setAccessKeyId("We recommend that you obtain the AccessKey ID of your RAM user from an environment variable");
config.setAccessKeySecret("We recommend that you obtain the AccessKey secret of your RAM user from an environment variable");
// Modify the region and endpoint as needed.
config.setRegionId("cn-shanghai");
config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
// Connection timeout period in milliseconds (ms).
config.setReadTimeout(6000);
// Read timeout period in milliseconds (ms).
config.setConnectTimeout(3000);
// Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
Client client = new Client(config);
JSONObject serviceParameters = new JSONObject();
// The taskId returned when the task was submitted.
serviceParameters.put("taskId", "The task ID returned for the moderation task.");
VoiceModerationCancelRequest voiceModerationCancelRequest = new VoiceModerationCancelRequest();
// Moderation type. audio_media_detection indicates audio file moderation, and live_stream_detection indicates audio live stream moderation.
voiceModerationCancelRequest.setService("live_stream_detection");
voiceModerationCancelRequest.setServiceParameters(serviceParameters.toJSONString());
try {
VoiceModerationCancelResponse response = client.voiceModerationCancel(voiceModerationCancelRequest);
if (response.getStatusCode() == 200) {
VoiceModerationCancelResponseBody result = response.getBody();
System.out.println("requestId=" + result.getRequestId());
System.out.println("code=" + result.getCode());
System.out.println("msg=" + result.getMessage());
if (200 != result.getCode()) {
System.out.println("voice moderation cancel not success. code:" + result.getCode());
}
} else {
System.out.println("response not success. status:" + response.getStatusCode());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Python SDK
Código-fonte: PyPI
Requer Python 3.6 ou superior.
Detectar áudio acessível publicamente
Instalar a dependência
pip install alibabacloud_green20220302==3.2.4
Enviar uma tarefa de moderação
# coding=utf-8
import os
import json
from alibabacloud_green20220302.client import Client
from alibabacloud_green20220302 import models
from alibabacloud_tea_openapi.models import Config
config = Config(
# Load credentials from environment variables.
# Do not hardcode your AccessKey pair in code.
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
connect_timeout=10000, # ms
read_timeout=3000, # ms
region_id='ap-southeast-1',
endpoint='green-cip.ap-southeast-1.aliyuncs.com'
)
# Reuse the client instance to avoid repeated connection creation.
client = Client(config)
service_parameters = {'url': 'https://example.com/sample.wav'}
request = models.VoiceModerationRequest(
service='audio_multilingual_global',
service_parameters=json.dumps(service_parameters)
)
try:
response = client.voice_moderation(request)
if response.status_code == 200:
result = response.body
if result.code == 200:
print('taskId:', result.data.task_id)
# Use taskId to poll for results.
else:
print('Moderation request failed. code:', result.code)
except Exception as err:
print(err)
Recuperar o resultado da moderação
# coding=utf-8
import os
import json
from alibabacloud_green20220302.client import Client
from alibabacloud_green20220302 import models
from alibabacloud_tea_openapi.models import Config
config = Config(
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
connect_timeout=10000,
read_timeout=3000,
region_id='ap-southeast-1',
endpoint='green-cip.ap-southeast-1.aliyuncs.com'
)
client = Client(config)
service_parameters = {'taskId': '<task-id>'}
request = models.VoiceModerationResultRequest(
service='audio_multilingual_global',
service_parameters=json.dumps(service_parameters)
)
try:
response = client.voice_moderation_result(request)
if response.status_code == 200:
result = response.body
if result.code == 200:
data = result.data
print('taskId:', data.task_id)
print('riskLevel:', data.risk_level)
print('sliceDetails:', data.slice_details)
else:
print('Failed to get result. code:', result.code)
except Exception as err:
print(err)
Detectar áudio local
Instalar as dependências
pip install alibabacloud_green20220302==3.2.4
Enviar uma tarefa de moderação
# coding=utf-8
import os
import json
import uuid
import time
import oss2
from alibabacloud_green20220302.client import Client
from alibabacloud_green20220302 import models
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util import models as util_models
is_vpc = False
token_dict = {}
bucket = None
def create_client(access_key_id, access_key_secret, endpoint):
config = Config(
access_key_id=access_key_id,
access_key_secret=access_key_secret,
endpoint=endpoint
)
return Client(config)
def init_oss_bucket(is_vpc, upload_token):
global bucket
auth = oss2.StsAuth(upload_token.access_key_id, upload_token.access_key_secret, upload_token.security_token)
end_point = upload_token.oss_internal_end_point if is_vpc else upload_token.oss_internet_end_point
# Reuse the bucket instance to avoid repeated connection creation.
bucket = oss2.Bucket(auth, end_point, upload_token.bucket_name)
def upload_file(file_path, upload_token):
init_oss_bucket(is_vpc, upload_token)
object_name = upload_token.file_name_prefix + str(uuid.uuid1()) + '.' + file_path.split('.')[-1]
bucket.put_object_from_file(object_name, file_path)
return object_name
def invoke(access_key_id, access_key_secret, endpoint):
# Reuse the client instance to avoid repeated connection creation.
client = create_client(access_key_id, access_key_secret, endpoint)
runtime = util_models.RuntimeOptions()
file_path = '/path/to/exampleFile.mp3'
# Get a temporary upload token (refresh if expired).
upload_token = token_dict.get(endpoint)
if upload_token is None or int(upload_token.expiration) <= int(time.time()):
response = client.describe_upload_token()
upload_token = response.body.data
token_dict[endpoint] = upload_token
object_name = upload_file(file_path, upload_token)
service_parameters = {
'ossBucketName': upload_token.bucket_name,
'ossObjectName': object_name,
'dataId': str(uuid.uuid4())
}
request = models.VoiceModerationRequest(
service='audio_multilingual_global',
service_parameters=json.dumps(service_parameters)
)
try:
return client.voice_moderation_with_options(request, runtime)
except Exception as err:
print(err)
if __name__ == '__main__':
access_key_id = os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
access_key_secret = os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
response = invoke(access_key_id, access_key_secret, 'green-cip.ap-southeast-1.aliyuncs.com')
if response and response.status_code == 200:
result = response.body
if result.code == 200:
print('taskId:', result.data.task_id)
Para recuperar os resultados, utilize o mesmo padrão descrito em Detectar áudio acessível publicamente.
Detectar áudio armazenado no OSS
Crie uma função de serviço para conceder acesso ao serviço de Moderação de Conteúdo para o seu bucket do OSS na página de Autorização de Acesso a Recursos da Nuvem.
Instalar a dependência
pip install alibabacloud_green20220302==3.2.4
Enviar uma tarefa de moderação
# coding=utf-8
import os
import json
from alibabacloud_green20220302.client import Client
from alibabacloud_green20220302 import models
from alibabacloud_tea_openapi.models import Config
config = Config(
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
connect_timeout=10000,
read_timeout=3000,
region_id='ap-southeast-1',
endpoint='green-cip.ap-southeast-1.aliyuncs.com'
)
client = Client(config)
service_parameters = {
'ossBucketName': '<your-bucket-name>',
'ossObjectName': 'voice/sample.mp3',
'ossRegionId': 'cn-shanghai'
}
request = models.VoiceModerationRequest(
service='audio_multilingual_global',
service_parameters=json.dumps(service_parameters)
)
try:
response = client.voice_moderation(request)
if response.status_code == 200:
result = response.body
if result.code == 200:
print('taskId:', result.data.task_id)
except Exception as err:
print(err)
Para recuperar os resultados, utilize o mesmo padrão descrito em Detectar áudio acessível publicamente.
PHP SDK
Código-fonte: Packagist
Requer PHP 5.6 ou superior.
Detectar áudio acessível publicamente
Instalar a dependência
composer require alibabacloud/green-20220302 3.2.4
Enviar uma tarefa de moderação
<?php
require('vendor/autoload.php');
use AlibabaCloud\SDK\Green\V20220302\Models\VoiceModerationResultRequest;
use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Green\V20220302\Green;
$config = new Config([]);
/**
* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
* We strongly recommend that you do not save your AccessKey ID and AccessKey secret in your project code. This can lead to an AccessKey pair leak and compromise the security of all resources in your account.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
$config->accessKeyId = "We recommend that you obtain the AccessKey ID of your RAM user from an environment variable";
$config->accessKeySecret = "We recommend that you obtain the AccessKey secret of your RAM user from an environment variable";
// Modify the region and endpoint as needed.
$config->regionId = "ap-southeast-1";
$config->endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
// Set an HTTP proxy.
// $config->httpProxy = "http://10.10.xx.xx:xxxx";
// Set an HTTPS proxy.
// $config->httpsProxy = "http://10.10.xx.xx:xxxx";
// Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
$client = new Green($config);
$request = new VoiceModerationResultRequest();
// Moderation type: audio_multilingual_global for multi-language audio moderation.
$request->service = "audio_multilingual_global";
// The taskId returned when the task was submitted.
$serviceParameters = array('taskId' => 'au_f_O5z5iaIis3iI0X2oNYj7qa-1x****');
$request->serviceParameters = json_encode($serviceParameters);
$runtime = new RuntimeOptions();
$runtime->readTimeout = 6000;
$runtime->connectTimeout = 3000;
try {
$response = $client->voiceModerationResult($request, $runtime);
print_r($response->body);
if (200 == $response->statusCode) {
$body = $response->body;
print_r("requestId = " . $body->requestId);
print_r("code = " . $body->code);
print_r("message = " . $body->message);
if (200 == $body->code) {
$data = $body->data;
print_r("liveId = " . $data->liveId);
print_r("sliceDetails = " . $data->sliceDetails);
print_r("taskId = " . $data->taskId);
print_r("url = " . $data->url);
} else {
print_r("voice moderation result not success. code:" . $body->code);
}
} else {
print_r("response not success. code:" . $response->statusCode);
}
} catch (TeaUnableRetryError $e) {
var_dump($e->getMessage());
var_dump($e->getErrorInfo());
var_dump($e->getLastException());
var_dump($e->getLastRequest());
}
<?php
require('vendor/autoload.php');
use AlibabaCloud\SDK\Green\V20220302\Models\VoiceModerationRequest;
use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Green\V20220302\Green;
$config = new Config([]);
/**
* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
* We strongly recommend that you do not save your AccessKey ID and AccessKey secret in your project code. This can lead to an AccessKey pair leak and compromise the security of all resources in your account.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
$config->accessKeyId = "We recommend that you obtain the AccessKey ID of your RAM user from an environment variable";
$config->accessKeySecret = "We recommend that you obtain the AccessKey secret of your RAM user from an environment variable";
// Modify the region and endpoint as needed.
$config->regionId = "ap-southeast-1";
$config->endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
// Set an HTTP proxy.
// $config->httpProxy = "http://10.10.xx.xx:xxxx";
// Set an HTTPS proxy.
// $config->httpsProxy = "http://10.10.xx.xx:xxxx";
// Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
$client = new Green($config);
$request = new VoiceModerationRequest();
// Moderation type: audio_multilingual_global for multi-language audio moderation.
$request->service = "audio_multilingual_global";
$serviceParameters = array(
// The file to be moderated. Example: voice/001.wav
'ossObjectName' => 'voice/001.wav',
// The region where the bucket of the file to be moderated is located. Example: cn-shanghai
'ossRegionId' => 'cn-shanghai',
// The name of the bucket that stores the file to be moderated. Example: bucket001
'ossBucketName' => 'bucket001',
// The unique ID of the data.
'dataId' => uniqid());
$request->serviceParameters = json_encode($serviceParameters);
$runtime = new RuntimeOptions();
$runtime->readTimeout = 6000;
$runtime->connectTimeout = 3000;
try {
$response = $client->voiceModeration($request, $runtime);
print_r($response->body);
if (200 == $response->statusCode) {
$body = $response->body;
print_r("requestId = " . $body->requestId);
print_r("code = " . $body->code);
print_r("message = " . $body->message);
if (200 == $body->code) {
$data = $body->data;
print_r("taskId = " . $data->taskId);
} else {
print_r("voice moderation not success. code:" . $body->code);
}
} else {
print_r("response not success. code:" . $response->statusCode);
}
} catch (TeaUnableRetryError $e) {
var_dump($e->getMessage());
var_dump($e->getErrorInfo());
var_dump($e->getLastException());
var_dump($e->getLastRequest());
}
<?php
require('vendor/autoload.php');
use AlibabaCloud\SDK\Green\V20220302\Models\VoiceModerationResultRequest;
use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Green\V20220302\Green;
$config = new Config([]);
/**
* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
* We strongly recommend that you do not save your AccessKey ID and AccessKey secret in your project code. This can lead to an AccessKey pair leak and compromise the security of all resources in your account.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
$config->accessKeyId = "We recommend that you obtain the AccessKey ID of your RAM user from an environment variable";
$config->accessKeySecret = "We recommend that you obtain the AccessKey secret of your RAM user from an environment variable";
// Modify the region and endpoint as needed.
$config->regionId = "ap-southeast-1";
$config->endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
// Set an HTTP proxy.
// $config->httpProxy = "http://10.10.xx.xx:xxxx";
// Set an HTTPS proxy.
// $config->httpsProxy = "http://10.10.xx.xx:xxxx";
// Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
$client = new Green($config);
$request = new VoiceModerationResultRequest();
// Moderation type: audio_multilingual_global for multi-language audio moderation.
$request->service = "audio_multilingual_global";
// The taskId returned when the task was submitted.
$serviceParameters = array('taskId' => 'au_f_O5z5iaIis3iI0X2oNYj7qa-1x****');
$request->serviceParameters = json_encode($serviceParameters);
$runtime = new RuntimeOptions();
$runtime->readTimeout = 6000;
$runtime->connectTimeout = 3000;
try {
$response = $client->voiceModerationResult($request, $runtime);
print_r($response->body);
if (200 == $response->statusCode) {
$body = $response->body;
print_r("requestId = " . $body->requestId);
print_r("code = " . $body->code);
print_r("message = " . $body->message);
if (200 == $body->code) {
$data = $body->data;
print_r("liveId = " . $data->liveId);
print_r("sliceDetails = " . $data->sliceDetails);
print_r("taskId = " . $data->taskId);
print_r("url = " . $data->url);
} else {
print_r("voice moderation result not success. code:" . $body->code);
}
} else {
print_r("response not success. code:" . $response->statusCode);
}
} catch (TeaUnableRetryError $e) {
var_dump($e->getMessage());
var_dump($e->getErrorInfo());
var_dump($e->getLastException());
var_dump($e->getLastRequest());
}
<?php
require('vendor/autoload.php');
use AlibabaCloud\SDK\Green\V20220302\Models\VoiceModerationResponse;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Green\V20220302\Green;
use AlibabaCloud\SDK\Green\V20220302\Models\VoiceModerationRequest;
use OSS\OssClient;
// Specifies whether the service is deployed in a VPC.
$isVPC = false;
// The token used to upload the file.
$tokenArray = array();
// The client used to upload the file.
$ossClient = null;
/**
* Create a client.
* @param $accessKeyId
* @param $accessKeySecret
* @param $endpoint
* @return Green
*/
function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
{
$config = new Config([
"accessKeyId" => $accessKeyId,
"accessKeySecret" => $accessKeySecret,
// Set an HTTP proxy.
// "httpProxy" => "http://10.10.xx.xx:xxxx",
// Set an HTTPS proxy.
// "httpsProxy" => "https://10.10.xx.xx:xxxx",
"endpoint" => $endpoint,
]);
return new Green($config);
}
/**
* Create a client to upload a file.
* @param $tokenData
* @return void
*/
function create_upload_client($tokenData): void
{
global $isVPC;
global $ossClient;
// Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
if ($isVPC) {
$ossClient = new OssClient($tokenData->accessKeyId, $tokenData->accessKeySecret, $tokenData->ossInternalEndPoint, false, $tokenData->securityToken);
} else {
$ossClient = new OssClient($tokenData->accessKeyId, $tokenData->accessKeySecret, $tokenData->ossInternetEndPoint, false, $tokenData->securityToken);
}
}
/**
* Upload a file.
* @param $fileName
* @param $tokenData
* @return string
* @throws \OSS\Core\OssException
*/
function upload_file($filePath, $tokenData): string
{
global $ossClient;
//Initialize OssClient.
create_upload_client($tokenData);
$split = explode(".", $filePath);
if (count($split) > 1) {
$objectName = $tokenData->fileNamePrefix . uniqid() . "." . explode(".", $filePath)[count($split) - 1];
} else {
$objectName = $tokenData->fileNamePrefix . uniqid();
}
//Upload the file.
$ossClient->uploadFile($tokenData->bucketName, $objectName, $filePath);
return $objectName;
}
/**
* Submit a moderation task.
* @param $accessKeyId
* @param $accessKeySecret
* @param $endpoint
* @return VoiceModerationResponse
* @throws \OSS\Core\OssException
*/
function invoke($accessKeyId, $accessKeySecret, $endpoint): VoiceModerationResponse
{
global $tokenArray;
// Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
$client = create_client($accessKeyId, $accessKeySecret, $endpoint);
// Create a RuntimeObject instance and set runtime parameters.
$runtime = new RuntimeOptions([]);
// The full path of the local file. Example: D:\\localPath\\exampleFile.mp3.
$filePath = "D:\\localPath\\exampleFile.mp3";
//Obtain a temporary token to upload the file.
if (!isset($tokenArray[$endpoint]) || $tokenArray[$endpoint]->expiration <= time()) {
$token = $client->describeUploadToken();
$tokenArray[$endpoint] = $token->body->data;
}
// Upload the file.
$objectName = upload_file($filePath, $tokenArray[$endpoint]);
// Construct moderation parameters.
$request = new VoiceModerationRequest();
// Moderation type: audio_multilingual_global for multi-language audio moderation.
$request->service = "audio_multilingual_global";
// The OSS information about the audio file to be moderated.
$serviceParameters = array(
'ossObjectName' => $objectName,
'ossBucketName' => $tokenArray[$endpoint]->bucketName,
'dataId' => uniqid());
$request->serviceParameters = json_encode($serviceParameters);
// Submit the moderation task.
return $client->voiceModerationWithOptions($request, $runtime);
}
/**
* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
* We strongly recommend that you do not save your AccessKey ID and AccessKey secret in your project code. This can lead to an AccessKey pair leak and compromise the security of all resources in your account.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
$accessKeyId = 'We recommend that you obtain the AccessKey ID of your RAM user from an environment variable';
$accessKeySecret = 'We recommend that you obtain the AccessKey secret of your RAM user from an environment variable';
// Modify the region and endpoint as needed.
$endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
try {
$response = invoke($accessKeyId, $accessKeySecret, $endpoint);
print_r(json_encode($response->body, JSON_UNESCAPED_UNICODE));
} catch (Exception $e) {
var_dump($e->getMessage());
var_dump($e->getErrorInfo());
var_dump($e->getLastException());
var_dump($e->getLastRequest());
}
Recuperar o resultado da moderação
Exemplo de código para cancelar uma tarefa de moderação de transmissão ao vivo
<?php
require('vendor/autoload.php');
use AlibabaCloud\SDK\Green\V20220302\Models\VoiceModerationCancelRequest;
use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Green\V20220302\Green;
$config = new Config([]);
/**
* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
* We strongly recommend that you do not save your AccessKey ID and AccessKey secret in your project code. This can lead to an AccessKey pair leak and compromise the security of all resources in your account.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
$config->accessKeyId = "We recommend that you obtain the AccessKey ID of your RAM user from an environment variable";
$config->accessKeySecret = "We recommend that you obtain the AccessKey secret of your RAM user from an environment variable";
// Modify the region and endpoint as needed.
$config->regionId = "cn-shanghai";
$config->endpoint = "green-cip.cn-shanghai.aliyuncs.com";
// Set an HTTP proxy.
// $config->httpProxy = "http://10.10.xx.xx:xxxx";
// Set an HTTPS proxy.
// $config->httpsProxy = "http://10.10.xx.xx:xxxx";
// Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
$client = new Green($config);
$request = new VoiceModerationCancelRequest();
// Moderation type. audio_media_detection for audio file moderation, live_stream_detection for audio live stream moderation.
$request->service = "audio_media_detection";
// The taskId returned when the task was submitted.
$serviceParameters = array('taskId' => 'au_f_O5z5iaIis3iI0X2oNYj7qa-1x****');
$request->serviceParameters = json_encode($serviceParameters);
$runtime = new RuntimeOptions();
$runtime->readTimeout = 6000;
$runtime->connectTimeout = 3000;
try {
$response = $client->voiceModerationCancel($request, $runtime);
print_r($response->body);
if (200 == $response->statusCode) {
$body = $response->body;
print_r("requestId = " . $body->requestId);
print_r("code = " . $body->code);
print_r("message = " . $body->message);
if (200 != $body->code) {
print_r("voice moderation cancel not success. code:" . $body->code);
}
} else {
print_r("response not success. code:" . $response->statusCode);
}
} catch (TeaUnableRetryError $e) {
var_dump($e->getMessage());
var_dump($e->getErrorInfo());
var_dump($e->getLastException());
var_dump($e->getLastRequest());
}
<?php
require('vendor/autoload.php');
use AlibabaCloud\SDK\Green\V20220302\Models\VoiceModerationResultRequest;
use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Green\V20220302\Green;
$config = new Config([]);
$config->accessKeyId = getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
$config->accessKeySecret = getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
$config->regionId = "ap-southeast-1";
$config->endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
$client = new Green($config);
$request = new VoiceModerationResultRequest();
$request->service = "audio_multilingual_global";
$serviceParameters = ['taskId' => '<task-id>'];
$request->serviceParameters = json_encode($serviceParameters);
$runtime = new RuntimeOptions();
$runtime->readTimeout = 6000;
$runtime->connectTimeout = 3000;
try {
$response = $client->voiceModerationResult($request, $runtime);
if (200 == $response->statusCode) {
$body = $response->body;
if (200 == $body->code) {
$data = $body->data;
echo "taskId: " . $data->taskId . PHP_EOL;
echo "riskLevel: " . $data->riskLevel . PHP_EOL;
echo "liveId: " . $data->liveId . PHP_EOL;
echo "url: " . $data->url . PHP_EOL;
echo "sliceDetails: " . json_encode($data->sliceDetails) . PHP_EOL;
}
}
} catch (TeaUnableRetryError $e) {
var_dump($e->getMessage());
}
Detectar áudio local
Instalar as dependências
composer require alibabacloud/green-20220302 3.2.4
Enviar uma tarefa de moderação
Para recuperar os resultados, utilize o mesmo padrão VoiceModerationResultRequest descrito em Detectar áudio acessível publicamente.
Exemplo de código para cancelar uma tarefa de moderação de transmissão ao vivo
<?php
require('vendor/autoload.php');
use AlibabaCloud\SDK\Green\V20220302\Models\VoiceModerationCancelRequest;
use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Green\V20220302\Green;
$config = new Config([]);
/**
* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
* We strongly recommend that you do not save your AccessKey ID and AccessKey secret in your project code. This can lead to an AccessKey pair leak and compromise the security of all resources in your account.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
$config->accessKeyId = "We recommend that you obtain the AccessKey ID of your RAM user from an environment variable";
$config->accessKeySecret = "We recommend that you obtain the AccessKey secret of your RAM user from an environment variable";
// Modify the region and endpoint as needed.
$config->regionId = "cn-shanghai";
$config->endpoint = "green-cip.cn-shanghai.aliyuncs.com";
// Set an HTTP proxy.
// $config->httpProxy = "http://10.10.xx.xx:xxxx";
// Set an HTTPS proxy.
// $config->httpsProxy = "http://10.10.xx.xx:xxxx";
// Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
$client = new Green($config);
$request = new VoiceModerationCancelRequest();
// Moderation type. audio_media_detection for audio file moderation, live_stream_detection for audio live stream moderation.
$request->service = "audio_media_detection";
// The taskId returned when the task was submitted.
$serviceParameters = array('taskId' => 'au_f_O5z5iaIis3iI0X2oNYj7qa-1x****');
$request->serviceParameters = json_encode($serviceParameters);
$runtime = new RuntimeOptions();
$runtime->readTimeout = 6000;
$runtime->connectTimeout = 3000;
try {
$response = $client->voiceModerationCancel($request, $runtime);
print_r($response->body);
if (200 == $response->statusCode) {
$body = $response->body;
print_r("requestId = " . $body->requestId);
print_r("code = " . $body->code);
print_r("message = " . $body->message);
if (200 != $body->code) {
print_r("voice moderation cancel not success. code:" . $body->code);
}
} else {
print_r("response not success. code:" . $response->statusCode);
}
} catch (TeaUnableRetryError $e) {
var_dump($e->getMessage());
var_dump($e->getErrorInfo());
var_dump($e->getLastException());
var_dump($e->getLastRequest());
}
Detectar áudio armazenado no OSS
Crie uma função de serviço na página de Autorização de Acesso a Recursos da Nuvem.
Instalar a dependência
composer require alibabacloud/green-20220302 3.2.4
Enviar uma tarefa de moderação
<?php
require('vendor/autoload.php');
use AlibabaCloud\SDK\Green\V20220302\Models\VoiceModerationRequest;
use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Green\V20220302\Green;
$config = new Config([]);
$config->accessKeyId = getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
$config->accessKeySecret = getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
$config->regionId = "ap-southeast-1";
$config->endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
$client = new Green($config);
$request = new VoiceModerationRequest();
$request->service = "audio_multilingual_global";
$serviceParameters = [
'ossObjectName' => 'voice/001.wav',
'ossRegionId' => 'cn-shanghai',
'ossBucketName' => '<your-bucket-name>',
'dataId' => uniqid()
];
$request->serviceParameters = json_encode($serviceParameters);
$runtime = new RuntimeOptions();
$runtime->readTimeout = 6000;
$runtime->connectTimeout = 3000;
try {
$response = $client->voiceModeration($request, $runtime);
if (200 == $response->statusCode && 200 == $response->body->code) {
echo "taskId: " . $response->body->data->taskId . PHP_EOL;
}
} catch (TeaUnableRetryError $e) {
var_dump($e->getMessage());
}
Para recuperar os resultados, utilize o mesmo padrão VoiceModerationResultRequest descrito em Detectar áudio acessível publicamente.
Exemplo de código para cancelar uma tarefa de moderação de transmissão ao vivo
<?php
require('vendor/autoload.php');
use AlibabaCloud\SDK\Green\V20220302\Models\VoiceModerationCancelRequest;
use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Green\V20220302\Green;
$config = new Config([]);
/**
* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
* We strongly recommend that you do not save your AccessKey ID and AccessKey secret in your project code. This can lead to an AccessKey pair leak and compromise the security of all resources in your account.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
$config->accessKeyId = "We recommend that you obtain the AccessKey ID of your RAM user from an environment variable";
$config->accessKeySecret = "We recommend that you obtain the AccessKey secret of your RAM user from an environment variable";
// Modify the region and endpoint as needed.
$config->regionId = "cn-shanghai";
$config->endpoint = "green-cip.cn-shanghai.aliyuncs.com";
// Set an HTTP proxy.
// $config->httpProxy = "http://10.10.xx.xx:xxxx";
// Set an HTTPS proxy.
// $config->httpsProxy = "http://10.10.xx.xx:xxxx";
// Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
$client = new Green($config);
$request = new VoiceModerationCancelRequest();
// Moderation type. audio_media_detection for audio file moderation, live_stream_detection for audio live stream moderation.
$request->service = "audio_media_detection";
// The taskId returned when the task was submitted.
$serviceParameters = array('taskId' => 'au_f_O5z5iaIis3iI0X2oNYj7qa-1x****');
$request->serviceParameters = json_encode($serviceParameters);
$runtime = new RuntimeOptions();
$runtime->readTimeout = 6000;
$runtime->connectTimeout = 3000;
try {
$response = $client->voiceModerationCancel($request, $runtime);
print_r($response->body);
if (200 == $response->statusCode) {
$body = $response->body;
print_r("requestId = " . $body->requestId);
print_r("code = " . $body->code);
print_r("message = " . $body->message);
if (200 != $body->code) {
print_r("voice moderation cancel not success. code:" . $body->code);
}
} else {
print_r("response not success. code:" . $response->statusCode);
}
} catch (TeaUnableRetryError $e) {
var_dump($e->getMessage());
var_dump($e->getErrorInfo());
var_dump($e->getLastException());
var_dump($e->getLastRequest());
}
Go SDK
Detectar áudio acessível publicamente
Instalar a dependência
go get github.com/alibabacloud-go/green-20220302/v3@v3.2.4
Enviar uma tarefa de moderação
package main
import (
"encoding/json"
"fmt"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
green "github.com/alibabacloud-go/green-20220302/v3/client"
"github.com/alibabacloud-go/tea/tea"
"net/http"
)
func main() {
config := &openapi.Config{
/**
* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
* We strongly recommend that you do not save your AccessKey ID and AccessKey secret in your project code. This can lead to an AccessKey pair leak and compromise the security of all resources in your account.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of your RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
* Obtain the AccessKey secret of your RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
*/
AccessKeyId: tea.String("We recommend that you obtain the AccessKey ID of your RAM user from an environment variable"),
AccessKeySecret: tea.String("We recommend that you obtain the AccessKey secret of your RAM user from an environment variable"),
// Specify your region.
RegionId: tea.String("ap-southeast-1"),
Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"),
// Set an HTTP proxy.
// HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"),
// Set an HTTPS proxy.
// HttpsProxy: tea.String("https://xx.xx.xx.xx:xxxx"),
/**
* Set a timeout period. The server-side timeout period for the entire link is 10 seconds. Set the timeout period accordingly.
* If the ReadTimeout value is less than the server-side processing time, a ReadTimeout exception is returned.
*/
ConnectTimeout: tea.Int(3000),
ReadTimeout: tea.Int(6000),
}
// Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
client, _err := green.NewClient(config)
if _err != nil {
panic(_err)
}
serviceParameters, _ := json.Marshal(
map[string]interface{}{
"taskId": "<Task ID>",
},
)
request := green.VoiceModerationResultRequest{
// The voice moderation service.
Service: tea.String("audio_multilingual_global"),
ServiceParameters: tea.String(string(serviceParameters)),
}
result, _err := client.VoiceModerationResult(&request)
if _err != nil {
panic(_err)
}
statusCode := tea.IntValue(tea.ToInt(result.StatusCode))
if statusCode == http.StatusOK {
voiceModerationResponse := result.Body
fmt.Println("response success. response:" + voiceModerationResponse.String())
if tea.IntValue(tea.ToInt(voiceModerationResponse.Code)) == 200 {
resultResponseBodyData := voiceModerationResponse.Data
fmt.Println("response liveId:" + tea.StringValue(resultResponseBodyData.LiveId))
fmt.Println("response sliceDetails:" + tea.ToString(resultResponseBodyData.SliceDetails))
} else {
fmt.Println("get voice moderation result not success. code:" + tea.ToString(tea.Int32Value(voiceModerationResponse.Code)))
}
} else {
fmt.Println("response not success. status:" + tea.ToString(statusCode))
}
}
package main
import (
"encoding/json"
"fmt"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
green "github.com/alibabacloud-go/green-20220302/v3/client"
"github.com/alibabacloud-go/tea/tea"
"net/http"
)
func main() {
config := &openapi.Config{
/**
* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
* We strongly recommend that you do not save your AccessKey ID and AccessKey secret in your project code. This can lead to an AccessKey pair leak and compromise the security of all resources in your account.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of your RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
* Obtain the AccessKey secret of your RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
*/
AccessKeyId: tea.String("We recommend that you obtain the AccessKey ID of your RAM user from an environment variable"),
AccessKeySecret: tea.String("We recommend that you obtain the AccessKey secret of your RAM user from an environment variable"),
// Specify your region.
RegionId: tea.String("ap-southeast-1"),
Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"),
// Set an HTTP proxy.
//HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"),
// Set an HTTPS proxy.
//HttpsProxy: tea.String("https://xx.xx.xx.xx:xxxx"),
/**
* Set a timeout period. The server-side timeout period for the entire link is 10 seconds. Set the timeout period accordingly.
* If the ReadTimeout value is less than the server-side processing time, a ReadTimeout exception is returned.
*/
ConnectTimeout: tea.Int(3000),
ReadTimeout: tea.Int(6000),
}
// Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
client, _err := green.NewClient(config)
if _err != nil {
panic(_err)
}
// The URL of the audio file to moderate.
serviceParameters, _ := json.Marshal(
map[string]interface{}{
//The region where the OSS bucket that stores the audio file is located. Example: cn-shanghai.
"ossRegionId": "cn-shanghai",
//The name of the OSS bucket that stores the audio file. Example: bucket001.
"ossBucketName":"bucket001",
//The name of the audio file object. Example: voice/001.wav.
"ossObjectName":"voice/001.wav",
//The ID of the data to be moderated.
"dataId": uuid.New().String(),
},
)
request := green.VoiceModerationRequest{
// The voice moderation service.
Service: tea.String("audio_multilingual_global"),
ServiceParameters: tea.String(string(serviceParameters)),
}
result, _err := client.VoiceModeration(&request)
if _err != nil {
panic(_err)
}
statusCode := tea.IntValue(tea.ToInt(result.StatusCode))
if statusCode == http.StatusOK {
voiceModerationResponse := result.Body
fmt.Println("response success. response:" + voiceModerationResponse.String())
if tea.IntValue(tea.ToInt(voiceModerationResponse.Code)) == 200 {
voiceModerationResponseData := voiceModerationResponse.Data
fmt.Println("response taskId:" + tea.StringValue(voiceModerationResponseData.TaskId))
} else {
fmt.Println("voice moderation not success. code:" + tea.ToString(tea.Int32Value(voiceModerationResponse.Code)))
}
} else {
fmt.Println("response not success. status:" + tea.ToString(statusCode))
}
}
package main
import (
"encoding/json"
"fmt"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
green "github.com/alibabacloud-go/green-20220302/v3/client"
"github.com/alibabacloud-go/tea/tea"
"net/http"
)
func main() {
config := &openapi.Config{
/**
* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
* We strongly recommend that you do not save your AccessKey ID and AccessKey secret in your project code. This can lead to an AccessKey pair leak and compromise the security of all resources in your account.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of your RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
* Obtain the AccessKey secret of your RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
*/
AccessKeyId: tea.String("We recommend that you obtain the AccessKey ID of your RAM user from an environment variable"),
AccessKeySecret: tea.String("We recommend that you obtain the AccessKey secret of your RAM user from an environment variable"),
// Specify your region.
RegionId: tea.String("ap-southeast-1"),
Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"),
// Set an HTTP proxy.
// HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"),
// Set an HTTPS proxy.
// HttpsProxy: tea.String("https://xx.xx.xx.xx:xxxx"),
/**
* Set a timeout period. The server-side timeout period for the entire link is 10 seconds. Set the timeout period accordingly.
* If the ReadTimeout value is less than the server-side processing time, a ReadTimeout exception is returned.
*/
ConnectTimeout: tea.Int(3000),
ReadTimeout: tea.Int(6000),
}
// Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
client, _err := green.NewClient(config)
if _err != nil {
panic(_err)
}
serviceParameters, _ := json.Marshal(
map[string]interface{}{
"taskId": "<Task ID>",
},
)
request := green.VoiceModerationResultRequest{
// The voice moderation service.
Service: tea.String("audio_multilingual_global"),
ServiceParameters: tea.String(string(serviceParameters)),
}
result, _err := client.VoiceModerationResult(&request)
if _err != nil {
panic(_err)
}
statusCode := tea.IntValue(tea.ToInt(result.StatusCode))
if statusCode == http.StatusOK {
voiceModerationResponse := result.Body
fmt.Println("response success. response:" + voiceModerationResponse.String())
if tea.IntValue(tea.ToInt(voiceModerationResponse.Code)) == 200 {
resultResponseBodyData := voiceModerationResponse.Data
fmt.Println("response liveId:" + tea.StringValue(resultResponseBodyData.LiveId))
fmt.Println("response sliceDetails:" + tea.ToString(resultResponseBodyData.SliceDetails))
} else {
fmt.Println("get voice moderation result not success. code:" + tea.ToString(tea.Int32Value(voiceModerationResponse.Code)))
}
} else {
fmt.Println("response not success. status:" + tea.ToString(statusCode))
}
}
package main
import (
"encoding/json"
"fmt"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
green20220302 "github.com/alibabacloud-go/green-20220302/v3/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/google/uuid"
"net/http"
"os"
"strings"
"time"
)
//The token used to upload the file.
var TokenMap =make(map[string]*green20220302.DescribeUploadTokenResponseBodyData)
//The client used to upload the file.
var Bucket *oss.Bucket
//Specifies whether the service is deployed in a VPC.
var isVPC = false
//Create a client.
func createClient(accessKeyId string, accessKeySecret string, endpoint string) (*green20220302.Client, error) {
config := &openapi.Config{
AccessKeyId: tea.String(accessKeyId),
AccessKeySecret: tea.String(accessKeySecret),
// Set an HTTP proxy.
// HttpProxy: tea.String("http://10.10.xx.xx:xxxx"),
// Set an HTTPS proxy.
// HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"),
Endpoint: tea.String(endpoint),
}
//Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
return green20220302.NewClient(config);
}
//Create a client to upload a file.
func createOssClient(tokenData *green20220302.DescribeUploadTokenResponseBodyData) {
if isVPC{
ossClient, err := oss.New(tea.StringValue(tokenData.OssInternalEndPoint), tea.StringValue(tokenData.AccessKeyId), tea.StringValue(tokenData.AccessKeySecret), oss.SecurityToken(tea.StringValue(tokenData.SecurityToken)))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
Bucket, _ =ossClient.Bucket(tea.StringValue(tokenData.BucketName));
}else {
ossClient, err := oss.New(tea.StringValue(tokenData.OssInternetEndPoint), tea.StringValue(tokenData.AccessKeyId), tea.StringValue(tokenData.AccessKeySecret), oss.SecurityToken(tea.StringValue(tokenData.SecurityToken)))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
Bucket, _ =ossClient.Bucket(tea.StringValue(tokenData.BucketName));
}
}
//Upload a file.
func uploadFile(filePath string,tokenData *green20220302.DescribeUploadTokenResponseBodyData) (string,error) {
createOssClient(tokenData)
objectName := tea.StringValue(tokenData.FileNamePrefix) + uuid.New().String() + "." + strings.Split(filePath, ".")[1]
//Upload the file.
_err := Bucket.PutObjectFromFile(objectName, filePath)
if _err != nil {
fmt.Println("Error:", _err)
os.Exit(-1)
}
return objectName,_err
}
func invoke(accessKeyId string, accessKeySecret string, endpoint string) (_result *green20220302.VoiceModerationResponse, _err error) {
//Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
client, _err := createClient(accessKeyId, accessKeySecret, endpoint)
if _err != nil {
return nil,_err
}
//Set runtime parameters. The settings take effect only on requests that use this runtime parameter instance.
runtime := &util.RuntimeOptions{}
//The full path of the local file. Example: D:\localPath\exampleFile.wav.
var filePath = "D:\\localPath\\exampleFile.wav"
//Obtain a temporary token to upload the file.
tokenData,ok:=TokenMap[endpoint];
if !ok || tea.Int32Value(tokenData.Expiration) <= int32(time.Now().Unix()) {
//Obtain a temporary token to upload the file.
uploadTokenResponse, _err := client.DescribeUploadToken()
if _err != nil {
return nil,_err
}
tokenData = uploadTokenResponse.Body.Data
TokenMap[endpoint] = tokenData
}
var objectName, _ = uploadFile(filePath,TokenMap[endpoint])
//Construct an audio moderation request.
serviceParameters, _ := json.Marshal(
map[string]interface{}{
"ossBucketName": tea.StringValue(TokenMap[endpoint].BucketName),
"ossObjectName": objectName,
"dataId": uuid.New().String(),
},
)
voiceModerationRequest := &green20220302.VoiceModerationRequest{
// The voice moderation service.
Service: tea.String("audio_multilingual_global"),
ServiceParameters: tea.String(string(serviceParameters)),
}
return client.VoiceModerationWithOptions(voiceModerationRequest, runtime)
}
func main() {
/**
* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
* We strongly recommend that you do not save your AccessKey ID and AccessKey secret in your project code. This can lead to an AccessKey pair leak and compromise the security of all resources in your account.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of your RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
* Obtain the AccessKey secret of your RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
*/
var accessKeyId= "We recommend that you obtain the AccessKey ID of your RAM user from an environment variable";
var accessKeySecret= "We recommend that you obtain the AccessKey secret of your RAM user from an environment variable";
//Modify the region and endpoint as needed.
var endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
response,_err := invoke(accessKeyId,accessKeySecret,endpoint)
flag := false
if _err != nil {
var err = &tea.SDKError{}
if _t, ok := _err.(*tea.SDKError); ok {
err = _t
if *err.StatusCode == 500 {
flag = true
}
}
}
if response == nil || *response.StatusCode == 500 || *response.Body.Code == 500 {
flag = true
}
//Automatic routing. The region is switched to ap-southeast-1.
if flag {
endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
response, _err = invoke(accessKeyId,accessKeySecret,endpoint)
}
if response != nil {
statusCode := tea.IntValue(tea.ToInt(response.StatusCode))
body := response.Body
voiceModerationResponseData := body.Data
fmt.Println("requestId:" + tea.StringValue(body.RequestId))
if statusCode == http.StatusOK {
fmt.Println("response success. response:" + body.String())
if tea.IntValue(tea.ToInt(body.Code)) == 200 {
result := voiceModerationResponseData.Result
fmt.Println("response dataId:" + tea.StringValue(voiceModerationResponseData.DataId))
for i := 0; i < len(result); i++ {
fmt.Println("response label:" + tea.StringValue(result[i].Label))
fmt.Println("response confidence:" + tea.ToString(tea.Float32Value(result[i].Confidence)))
}
} else {
fmt.Println("voice moderation not success. status" + tea.ToString(body.Code))
}
} else {
fmt.Print("response not success. status:" + tea.ToString(statusCode))
}
}
}
package main
import (
"encoding/json"
"fmt"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
green "github.com/alibabacloud-go/green-20220302/v3/client"
"github.com/alibabacloud-go/tea/tea"
"net/http"
)
func main() {
config := &openapi.Config{
/**
* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
* We strongly recommend that you do not save your AccessKey ID and AccessKey secret in your project code. This can lead to an AccessKey pair leak and compromise the security of all resources in your account.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of your RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
* Obtain the AccessKey secret of your RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
*/
AccessKeyId: tea.String("We recommend that you obtain the AccessKey ID of your RAM user from an environment variable"),
AccessKeySecret: tea.String("We recommend that you obtain the AccessKey secret of your RAM user from an environment variable"),
// Specify your region.
RegionId: tea.String("ap-southeast-1"),
Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"),
// Set an HTTP proxy.
// HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"),
// Set an HTTPS proxy.
// HttpsProxy: tea.String("https://xx.xx.xx.xx:xxxx"),
/**
* Set a timeout period. The server-side timeout period for the entire link is 10 seconds. Set the timeout period accordingly.
* If the ReadTimeout value is less than the server-side processing time, a ReadTimeout exception is returned.
*/
ConnectTimeout: tea.Int(3000),
ReadTimeout: tea.Int(6000),
}
// Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
client, _err := green.NewClient(config)
if _err != nil {
panic(_err)
}
serviceParameters, _ := json.Marshal(
map[string]interface{}{
"taskId": "<Task ID>",
},
)
request := green.VoiceModerationResultRequest{
// The voice moderation service.
Service: tea.String("audio_multilingual_global"),
ServiceParameters: tea.String(string(serviceParameters)),
}
result, _err := client.VoiceModerationResult(&request)
if _err != nil {
panic(_err)
}
statusCode := tea.IntValue(tea.ToInt(result.StatusCode))
if statusCode == http.StatusOK {
voiceModerationResponse := result.Body
fmt.Println("response success. response:" + voiceModerationResponse.String())
if tea.IntValue(tea.ToInt(voiceModerationResponse.Code)) == 200 {
resultResponseBodyData := voiceModerationResponse.Data
fmt.Println("response liveId:" + tea.StringValue(resultResponseBodyData.LiveId))
fmt.Println("response sliceDetails:" + tea.ToString(resultResponseBodyData.SliceDetails))
} else {
fmt.Println("get voice moderation result not success. code:" + tea.ToString(tea.Int32Value(voiceModerationResponse.Code)))
}
} else {
fmt.Println("response not success. status:" + tea.ToString(statusCode))
}
}
Recuperar o resultado da moderação
Exemplo de código para cancelar uma tarefa de moderação de transmissão ao vivo
package main
import (
"encoding/json"
"fmt"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
green "github.com/alibabacloud-go/green-20220302/v3/client"
"github.com/alibabacloud-go/tea/tea"
"net/http"
)
func main() {
config := &openapi.Config{
/**
* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
* We strongly recommend that you do not save your AccessKey ID and AccessKey secret in your project code. This can lead to an AccessKey pair leak and compromise the security of all resources in your account.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of your RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
* Obtain the AccessKey secret of your RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
*/
AccessKeyId: tea.String("We recommend that you obtain the AccessKey ID of your RAM user from an environment variable"),
AccessKeySecret: tea.String("We recommend that you obtain the AccessKey secret of your RAM user from an environment variable"),
// Specify your region.
RegionId: tea.String("cn-shanghai"),
Endpoint: tea.String("green-cip.cn-shanghai.aliyuncs.com"),
// Set an HTTP proxy.
// HttpProxy: tea.String("http://10.10.xx.xx:xxxx"),
// Set an HTTPS proxy.
// HttpsProxy: tea.String("https://10.10.xx.xx:xxxx"),
/**
* Set a timeout period. The server-side timeout period for the entire link is 10 seconds. Set the timeout period accordingly.
* If the ReadTimeout value is less than the server-side processing time, a ReadTimeout exception is returned.
*/
ConnectTimeout: tea.Int(3000),
ReadTimeout: tea.Int(6000),
}
// Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
client, _err := green.NewClient(config)
if _err != nil {
panic(_err)
}
serviceParameters, _ := json.Marshal(
map[string]interface{}{
"taskId": "<The ID of the task to cancel>",
},
)
request := green.VoiceModerationCancelRequest{
// The voice moderation service.
Service: tea.String("audio_media_detection"),
ServiceParameters: tea.String(string(serviceParameters)),
}
result, _err := client.VoiceModerationCancel(&request)
if _err != nil {
panic(_err)
}
statusCode := tea.IntValue(tea.ToInt(result.StatusCode))
if statusCode == http.StatusOK {
cancelResponseBody := result.Body
fmt.Println("response success. response:" + cancelResponseBody.String())
if tea.IntValue(tea.ToInt(cancelResponseBody.Code)) != 200 {
fmt.Println("voice moderation cancel not success. code:" + tea.ToString(tea.Int32Value(cancelResponseBody.Code)))
}
} else {
fmt.Println("response not success. status:" + tea.ToString(statusCode))
}
}
package main
import (
"encoding/json"
"fmt"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
green "github.com/alibabacloud-go/green-20220302/v3/client"
"github.com/alibabacloud-go/tea/tea"
"net/http"
"os"
)
func main() {
config := &openapi.Config{
AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
RegionId: tea.String("ap-southeast-1"),
Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"),
ConnectTimeout: tea.Int(3000),
ReadTimeout: tea.Int(6000),
}
client, err := green.NewClient(config)
if err != nil {
panic(err)
}
serviceParameters, _ := json.Marshal(map[string]interface{}{
"taskId": "<task-id>",
})
request := green.VoiceModerationResultRequest{
Service: tea.String("audio_multilingual_global"),
ServiceParameters: tea.String(string(serviceParameters)),
}
result, err := client.VoiceModerationResult(&request)
if err != nil {
panic(err)
}
if tea.IntValue(tea.ToInt(result.StatusCode)) == http.StatusOK {
body := result.Body
if tea.IntValue(tea.ToInt(body.Code)) == 200 {
data := body.Data
fmt.Println("taskId:", tea.StringValue(data.TaskId))
fmt.Println("riskLevel:", tea.StringValue(data.RiskLevel))
fmt.Println("liveId:", tea.StringValue(data.LiveId))
fmt.Println("sliceDetails:", tea.ToString(data.SliceDetails))
}
}
}
Detectar áudio local
Instalar as dependências
go get github.com/alibabacloud-go/green-20220302/v3@v3.2.4
Para obter o código de exemplo completo em Go para moderação de áudio local, gere-o utilizando o OpenAPI Explorer.
Exemplo de código para cancelar uma tarefa de moderação de transmissão ao vivo
package main
import (
"encoding/json"
"fmt"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
green "github.com/alibabacloud-go/green-20220302/v3/client"
"github.com/alibabacloud-go/tea/tea"
"net/http"
)
func main() {
config := &openapi.Config{
/**
* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
* We strongly recommend that you do not save your AccessKey ID and AccessKey secret in your project code. This can lead to an AccessKey pair leak and compromise the security of all resources in your account.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of your RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
* Obtain the AccessKey secret of your RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
*/
AccessKeyId: tea.String("We recommend that you obtain the AccessKey ID of your RAM user from an environment variable"),
AccessKeySecret: tea.String("We recommend that you obtain the AccessKey secret of your RAM user from an environment variable"),
// Specify your region.
RegionId: tea.String("cn-shanghai"),
Endpoint: tea.String("green-cip.cn-shanghai.aliyuncs.com"),
// Set an HTTP proxy.
// HttpProxy: tea.String("http://10.10.xx.xx:xxxx"),
// Set an HTTPS proxy.
// HttpsProxy: tea.String("https://10.10.xx.xx:xxxx"),
/**
* Set a timeout period. The server-side timeout period for the entire link is 10 seconds. Set the timeout period accordingly.
* If the ReadTimeout value is less than the server-side processing time, a ReadTimeout exception is returned.
*/
ConnectTimeout: tea.Int(3000),
ReadTimeout: tea.Int(6000),
}
// Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
client, _err := green.NewClient(config)
if _err != nil {
panic(_err)
}
serviceParameters, _ := json.Marshal(
map[string]interface{}{
"taskId": "<The ID of the task to cancel>",
},
)
request := green.VoiceModerationCancelRequest{
// The voice moderation service.
Service: tea.String("audio_media_detection"),
ServiceParameters: tea.String(string(serviceParameters)),
}
result, _err := client.VoiceModerationCancel(&request)
if _err != nil {
panic(_err)
}
statusCode := tea.IntValue(tea.ToInt(result.StatusCode))
if statusCode == http.StatusOK {
cancelResponseBody := result.Body
fmt.Println("response success. response:" + cancelResponseBody.String())
if tea.IntValue(tea.ToInt(cancelResponseBody.Code)) != 200 {
fmt.Println("voice moderation cancel not success. code:" + tea.ToString(tea.Int32Value(cancelResponseBody.Code)))
}
} else {
fmt.Println("response not success. status:" + tea.ToString(statusCode))
}
}
Detectar áudio armazenado no OSS
Caso de uso
Se os arquivos de áudio estiverem armazenados no Alibaba Cloud OSS, autorize o serviço Content Moderation a acessar o OSS criando uma função de serviço. O Voice Moderation 2.0 acessa os arquivos do OSS para moderação por meio dessa função de serviço. Acesse a página Cloud Resource Access Authorization para criar uma função de serviço.
-
Execute o comando a seguir para instalar a dependência.
go get github.com/alibabacloud-go/green-20220302/v3@v3.2.4 -
Utilize o SDK Go.
-
Código de exemplo para enviar uma tarefa de moderação de voz
package main import ( "encoding/json" "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" green "github.com/alibabacloud-go/green-20220302/v3/client" "github.com/alibabacloud-go/tea/tea" "net/http" ) func main() { config := &openapi.Config{ /** * An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user for API calls or routine O&M. * We strongly recommend that you do not save your AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. * Common methods to obtain environment variables: * Obtain the AccessKey ID of your RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID") * Obtain the AccessKey secret of your RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ AccessKeyId: tea.String("We recommend that you obtain the AccessKey ID of your RAM user from an environment variable"), AccessKeySecret: tea.String("We recommend that you obtain the AccessKey secret of your RAM user from an environment variable"), // Specify your region. RegionId: tea.String("ap-southeast-1"), Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"), // Set the HTTP proxy. //HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"), // Set the HTTPS proxy. //HttpsProxy: tea.String("https://xx.xx.xx.xx:xxxx"), /** * The server-side timeout is 10 seconds. Set ConnectTimeout and ReadTimeout accordingly. * If ReadTimeout is less than the server processing time, a ReadTimeout exception occurs. */ ConnectTimeout: tea.Int(3000), ReadTimeout: tea.Int(6000), } // Note: Reuse the client instance to avoid repeated connection creation. client, _err := green.NewClient(config) if _err != nil { panic(_err) } // URL of the audio to moderate. serviceParameters, _ := json.Marshal( map[string]interface{}{ // Region of the OSS bucket. Example: cn-shanghai "ossRegionId": "cn-shanghai", // Name of the OSS bucket. Example: bucket001 "ossBucketName":"bucket001", // Object name of the audio file. Example: voice/001.wav "ossObjectName":"voice/001.wav", // Data ID of the audio to moderate. "dataId": uuid.New().String(), }, ) request := green.VoiceModerationRequest{ // Voice moderation service code. Service: tea.String("audio_multilingual_global"), ServiceParameters: tea.String(string(serviceParameters)), } result, _err := client.VoiceModeration(&request) if _err != nil { panic(_err) } statusCode := tea.IntValue(tea.ToInt(result.StatusCode)) if statusCode == http.StatusOK { voiceModerationResponse := result.Body fmt.Println("response success. response:" + voiceModerationResponse.String()) if tea.IntValue(tea.ToInt(voiceModerationResponse.Code)) == 200 { voiceModerationResponseData := voiceModerationResponse.Data fmt.Println("response taskId:" + tea.StringValue(voiceModerationResponseData.TaskId)) } else { fmt.Println("voice moderation not success. code:" + tea.ToString(tea.Int32Value(voiceModerationResponse.Code))) } } else { fmt.Println("response not success. status:" + tea.ToString(statusCode)) } } -
Código de exemplo para obter resultados de moderação de voz
package main import ( "encoding/json" "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" green "github.com/alibabacloud-go/green-20220302/v3/client" "github.com/alibabacloud-go/tea/tea" "net/http" ) func main() { config := &openapi.Config{ /** * An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user for API calls or routine O&M. * We strongly recommend that you do not save your AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. * Common methods to obtain environment variables: * Obtain the AccessKey ID of your RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID") * Obtain the AccessKey secret of your RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ AccessKeyId: tea.String("We recommend that you obtain the AccessKey ID of your RAM user from an environment variable"), AccessKeySecret: tea.String("We recommend that you obtain the AccessKey secret of your RAM user from an environment variable"), // Specify your region. RegionId: tea.String("ap-southeast-1"), Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"), // Set the HTTP proxy. // HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"), // Set the HTTPS proxy. // HttpsProxy: tea.String("https://xx.xx.xx.xx:xxxx"), /** * The server-side timeout is 10 seconds. Set ConnectTimeout and ReadTimeout accordingly. * If ReadTimeout is less than the server processing time, a ReadTimeout exception occurs. */ ConnectTimeout: tea.Int(3000), ReadTimeout: tea.Int(6000), } // Note: Reuse the client instance to avoid repeated connection creation. client, _err := green.NewClient(config) if _err != nil { panic(_err) } serviceParameters, _ := json.Marshal( map[string]interface{}{ "taskId": "<Task ID>", }, ) request := green.VoiceModerationResultRequest{ // Voice moderation service code. Service: tea.String("audio_multilingual_global"), ServiceParameters: tea.String(string(serviceParameters)), } result, _err := client.VoiceModerationResult(&request) if _err != nil { panic(_err) } statusCode := tea.IntValue(tea.ToInt(result.StatusCode)) if statusCode == http.StatusOK { voiceModerationResponse := result.Body fmt.Println("response success. response:" + voiceModerationResponse.String()) if tea.IntValue(tea.ToInt(voiceModerationResponse.Code)) == 200 { resultResponseBodyData := voiceModerationResponse.Data fmt.Println("response liveId:" + tea.StringValue(resultResponseBodyData.LiveId)) fmt.Println("response sliceDetails:" + tea.ToString(resultResponseBodyData.SliceDetails)) } else { fmt.Println("get voice moderation result not success. code:" + tea.ToString(tea.Int32Value(voiceModerationResponse.Code))) } } else { fmt.Println("response not success. status:" + tea.ToString(statusCode)) } }
-
C# SDK
Código-fonte: NuGet
Detectar áudio acessível publicamente
Instalar a dependência
dotnet add package AlibabaCloud.SDK.Green20220302 --version 3.2.4
Enviar uma tarefa de moderação
using Newtonsoft.Json;
using Tea;
namespace AlibabaCloud.SDK.Sample
{
public class Sample
{
/**
* Use an AccessKey ID and AccessKey secret to initialize the client.
* @param accessKeyId
* @param accessKeySecret
* @return Client
* @throws Exception
*/
public static AlibabaCloud.SDK.Green20220302.Client CreateClient(string accessKeyId, string accessKeySecret)
{
AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
{
AccessKeyId = accessKeyId,
AccessKeySecret = accessKeySecret,
};
// The endpoint of the service.
config.Endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
return new AlibabaCloud.SDK.Green20220302.Client(config);
}
public static void Main(string[] args)
{
// Hard-coding an AccessKey pair in your project code can lead to an AccessKey pair leak and compromise the security of all resources in your account. The following code is for reference only. We recommend that you use a more secure method, such as using a Security Token Service (STS) token.
/**
* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
* We strongly recommend that you do not save your AccessKey ID and AccessKey secret in your project code. This can lead to an AccessKey pair leak and compromise the security of all resources in your account.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of your RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
* Obtain the AccessKey secret of your RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
*/
string accessKeyId = "We recommend that you obtain the AccessKey ID of your RAM user from an environment variable",
string accessKeySecret = 'We recommend that you obtain the AccessKey secret of your RAM user from an environment variable',
// Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
AlibabaCloud.SDK.Green20220302.Client client = CreateClient(accessKeyId, accessKeySecret);
// Construct a voice moderation request.
AlibabaCloud.SDK.Green20220302.Models.VoiceModerationResultRequest voiceModerationResultRequest = new AlibabaCloud.SDK.Green20220302.Models.VoiceModerationResultRequest();
// The voice moderation service.
voiceModerationResultRequest.Service="audio_multilingual_global";
Dictionary<String,Object> task=new Dictionary<string, object>();
// The ID of the task whose result you want to query.
task.Add("taskId","<The ID of the task whose result you want to query>");
voiceModerationResultRequest.ServiceParameters=JsonConvert.SerializeObject(task);
// Create a RuntimeObject instance and set runtime parameters.
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
runtime.ReadTimeout = 10000;
runtime.ConnectTimeout = 10000;
try
{
// Submit the voice moderation task.
AlibabaCloud.SDK.Green20220302.Models.VoiceModerationResultResponse response= client.VoiceModerationResultWithOptions(voiceModerationResultRequest, runtime);
if(response is not null){
Console.WriteLine("response statusCode : "+response.StatusCode);
if (response.Body is not null){
Console.WriteLine("requestId : " + response.Body.RequestId);
Console.WriteLine("code : " + response.Body.Code);
Console.WriteLine("message : " + response.Body.Message);
if(response.Body.Data is not null){
Console.WriteLine("taskId : " + response.Body.Data.TaskId);
Console.WriteLine("liveId : " + response.Body.Data.LiveId);
Console.WriteLine("url : " + response.Body.Data.Url);
Console.WriteLine("sliceDetails : " + JsonConvert.SerializeObject(response.Body.Data.SliceDetails));
}
}
}
}
catch (TeaException error)
{
// Print the error if necessary.
AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
Console.WriteLine("error : " + error);
}
catch (Exception _error)
{
TeaException error = new TeaException(new Dictionary<string, object>
{
{ "message", _error.Message }
});
// Print the error if necessary.
AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
Console.WriteLine("error : " + error);
}
}
}
}
using Newtonsoft.Json;
using Tea;
namespace AlibabaCloud.SDK.Sample
{
public class Sample
{
/**
* Use an AccessKey ID and AccessKey secret to initialize the client.
* @param accessKeyId
* @param accessKeySecret
* @return Client
* @throws Exception
*/
public static AlibabaCloud.SDK.Green20220302.Client CreateClient(string accessKeyId, string accessKeySecret)
{
AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
{
AccessKeyId = accessKeyId,
AccessKeySecret = accessKeySecret,
};
// The endpoint of the service.
config.Endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
return new AlibabaCloud.SDK.Green20220302.Client(config);
}
public static void Main(string[] args)
{
// Hard-coding an AccessKey pair in your project code can lead to an AccessKey pair leak and compromise the security of all resources in your account. The following code is for reference only. We recommend that you use a more secure method, such as using a Security Token Service (STS) token.
/**
* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
* We strongly recommend that you do not save your AccessKey ID and AccessKey secret in your project code. This can lead to an AccessKey pair leak and compromise the security of all resources in your account.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of your RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
* Obtain the AccessKey secret of your RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
*/
string accessKeyId = "We recommend that you obtain the AccessKey ID of your RAM user from an environment variable",
string accessKeySecret = 'We recommend that you obtain the AccessKey secret of your RAM user from an environment variable',
// Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
AlibabaCloud.SDK.Green20220302.Client client = CreateClient(accessKeyId, accessKeySecret);
// Construct a voice moderation request.
AlibabaCloud.SDK.Green20220302.Models.VoiceModerationRequest voiceModerationRequest = new AlibabaCloud.SDK.Green20220302.Models.VoiceModerationRequest();
// The voice moderation service.
voiceModerationRequest.Service="audio_multilingual_global";
Dictionary<String,Object> task=new Dictionary<string, object>();
// Example of passing OSS file parameters.
task.Add("ossBucketName","bucket_01");
task.Add("ossObjectName","test/sample.wav");
task.Add("ossRegionId","cn-shanghai");
voiceModerationRequest.ServiceParameters=JsonConvert.SerializeObject(task);
// Create a RuntimeObject instance and set runtime parameters.
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
runtime.ReadTimeout = 10000;
runtime.ConnectTimeout = 10000;
try
{
// Submit the voice moderation task.
AlibabaCloud.SDK.Green20220302.Models.VoiceModerationResponse response= client.VoiceModerationWithOptions(voiceModerationRequest, runtime);
if(response is not null){
Console.WriteLine("response statusCode : "+response.StatusCode);
if (response.Body is not null){
Console.WriteLine("requestId : " + response.Body.RequestId);
Console.WriteLine("code : " + response.Body.Code);
Console.WriteLine("message : " + response.Body.Message);
if(response.Body.Data is not null){
Console.WriteLine("taskId : " + response.Body.Data.TaskId);
}
}
}
}
catch (TeaException error)
{
// Print the error if necessary.
AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
Console.WriteLine("error : " + error);
}
catch (Exception _error)
{
TeaException error = new TeaException(new Dictionary<string, object>
{
{ "message", _error.Message }
});
// Print the error if necessary.
AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
Console.WriteLine("error : " + error);
}
}
}
}
using Newtonsoft.Json;
using Tea;
namespace AlibabaCloud.SDK.Sample
{
public class Sample
{
/**
* Use an AccessKey ID and AccessKey secret to initialize the client.
* @param accessKeyId
* @param accessKeySecret
* @return Client
* @throws Exception
*/
public static AlibabaCloud.SDK.Green20220302.Client CreateClient(string accessKeyId, string accessKeySecret)
{
AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
{
AccessKeyId = accessKeyId,
AccessKeySecret = accessKeySecret,
};
// The endpoint of the service.
config.Endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
return new AlibabaCloud.SDK.Green20220302.Client(config);
}
public static void Main(string[] args)
{
// Hard-coding an AccessKey pair in your project code can lead to an AccessKey pair leak and compromise the security of all resources in your account. The following code is for reference only. We recommend that you use a more secure method, such as using a Security Token Service (STS) token.
/**
* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
* We strongly recommend that you do not save your AccessKey ID and AccessKey secret in your project code. This can lead to an AccessKey pair leak and compromise the security of all resources in your account.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of your RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
* Obtain the AccessKey secret of your RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
*/
string accessKeyId = "We recommend that you obtain the AccessKey ID of your RAM user from an environment variable",
string accessKeySecret = 'We recommend that you obtain the AccessKey secret of your RAM user from an environment variable',
// Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
AlibabaCloud.SDK.Green20220302.Client client = CreateClient(accessKeyId, accessKeySecret);
// Construct a voice moderation request.
AlibabaCloud.SDK.Green20220302.Models.VoiceModerationResultRequest voiceModerationResultRequest = new AlibabaCloud.SDK.Green20220302.Models.VoiceModerationResultRequest();
// The voice moderation service.
voiceModerationResultRequest.Service="audio_multilingual_global";
Dictionary<String,Object> task=new Dictionary<string, object>();
// The ID of the task whose result you want to query.
task.Add("taskId","<The ID of the task whose result you want to query>");
voiceModerationResultRequest.ServiceParameters=JsonConvert.SerializeObject(task);
// Create a RuntimeObject instance and set runtime parameters.
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
runtime.ReadTimeout = 10000;
runtime.ConnectTimeout = 10000;
try
{
// Submit the voice moderation task.
AlibabaCloud.SDK.Green20220302.Models.VoiceModerationResultResponse response= client.VoiceModerationResultWithOptions(voiceModerationResultRequest, runtime);
if(response is not null){
Console.WriteLine("response statusCode : "+response.StatusCode);
if (response.Body is not null){
Console.WriteLine("requestId : " + response.Body.RequestId);
Console.WriteLine("code : " + response.Body.Code);
Console.WriteLine("message : " + response.Body.Message);
if(response.Body.Data is not null){
Console.WriteLine("taskId : " + response.Body.Data.TaskId);
Console.WriteLine("liveId : " + response.Body.Data.LiveId);
Console.WriteLine("url : " + response.Body.Data.Url);
Console.WriteLine("sliceDetails : " + JsonConvert.SerializeObject(response.Body.Data.SliceDetails));
}
}
}
}
catch (TeaException error)
{
// Print the error if necessary.
AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
Console.WriteLine("error : " + error);
}
catch (Exception _error)
{
TeaException error = new TeaException(new Dictionary<string, object>
{
{ "message", _error.Message }
});
// Print the error if necessary.
AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
Console.WriteLine("error : " + error);
}
}
}
}
using Newtonsoft.Json;
using Tea;
namespace AlibabaCloud.SDK.Sample
{
public class Sample
{
/**
* Use an AccessKey ID and AccessKey secret to initialize the client.
* @param accessKeyId
* @param accessKeySecret
* @return Client
* @throws Exception
*/
public static AlibabaCloud.SDK.Green20220302.Client CreateClient(string accessKeyId, string accessKeySecret)
{
AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
{
AccessKeyId = accessKeyId,
AccessKeySecret = accessKeySecret,
};
// The endpoint of the service.
config.Endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
return new AlibabaCloud.SDK.Green20220302.Client(config);
}
public static void Main(string[] args)
{
// Hard-coding an AccessKey pair in your project code can lead to an AccessKey pair leak and compromise the security of all resources in your account. The following code is for reference only. We recommend that you use a more secure method, such as using a Security Token Service (STS) token.
/**
* An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
* We strongly recommend that you do not save your AccessKey ID and AccessKey secret in your project code. This can lead to an AccessKey pair leak and compromise the security of all resources in your account.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of your RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
* Obtain the AccessKey secret of your RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
*/
string accessKeyId = "We recommend that you obtain the AccessKey ID of your RAM user from an environment variable",
string accessKeySecret = 'We recommend that you obtain the AccessKey secret of your RAM user from an environment variable',
// Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation.
AlibabaCloud.SDK.Green20220302.Client client = CreateClient(accessKeyId, accessKeySecret);
// Construct a voice moderation request.
AlibabaCloud.SDK.Green20220302.Models.VoiceModerationResultRequest voiceModerationResultRequest = new AlibabaCloud.SDK.Green20220302.Models.VoiceModerationResultRequest();
// The voice moderation service.
voiceModerationResultRequest.Service="audio_multilingual_global";
Dictionary<String,Object> task=new Dictionary<string, object>();
// The ID of the task whose result you want to query.
task.Add("taskId","<The ID of the task whose result you want to query>");
voiceModerationResultRequest.ServiceParameters=JsonConvert.SerializeObject(task);
// Create a RuntimeObject instance and set runtime parameters.
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
runtime.ReadTimeout = 10000;
runtime.ConnectTimeout = 10000;
try
{
// Submit the voice moderation task.
AlibabaCloud.SDK.Green20220302.Models.VoiceModerationResultResponse response= client.VoiceModerationResultWithOptions(voiceModerationResultRequest, runtime);
if(response is not null){
Console.WriteLine("response statusCode : "+response.StatusCode);
if (response.Body is not null){
Console.WriteLine("requestId : " + response.Body.RequestId);
Console.WriteLine("code : " + response.Body.Code);
Console.WriteLine("message : " + response.Body.Message);
if(response.Body.Data is not null){
Console.WriteLine("taskId : " + response.Body.Data.TaskId);
Console.WriteLine("liveId : " + response.Body.Data.LiveId);
Console.WriteLine("url : " + response.Body.Data.Url);
Console.WriteLine("sliceDetails : " + JsonConvert.SerializeObject(response.Body.Data.SliceDetails));
}
}
}
}
catch (TeaException error)
{
// Print the error if necessary.
AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
Console.WriteLine("error : " + error);
}
catch (Exception _error)
{
TeaException error = new TeaException(new Dictionary<string, object>
{
{ "message", _error.Message }
});
// Print the error if necessary.
AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
Console.WriteLine("error : " + error);
}
}
}
}
Obter o resultado da moderação
using Newtonsoft.Json;
using Tea;
namespace AlibabaCloud.SDK.Sample
{
public class Sample
{
public static AlibabaCloud.SDK.Green20220302.Client CreateClient(string accessKeyId, string accessKeySecret)
{
AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
{
AccessKeyId = accessKeyId,
AccessKeySecret = accessKeySecret,
};
config.Endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
return new AlibabaCloud.SDK.Green20220302.Client(config);
}
public static void Main(string[] args)
{
string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID");
string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
AlibabaCloud.SDK.Green20220302.Client client = CreateClient(accessKeyId, accessKeySecret);
AlibabaCloud.SDK.Green20220302.Models.VoiceModerationResultRequest request =
new AlibabaCloud.SDK.Green20220302.Models.VoiceModerationResultRequest();
request.Service = "audio_multilingual_global";
Dictionary<string, object> task = new Dictionary<string, object>();
task.Add("taskId", "<task-id>");
request.ServiceParameters = JsonConvert.SerializeObject(task);
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
runtime.ReadTimeout = 6000;
runtime.ConnectTimeout = 3000;
try
{
AlibabaCloud.SDK.Green20220302.Models.VoiceModerationResultResponse response =
client.VoiceModerationResultWithOptions(request, runtime);
if (response != null && response.Body != null && response.Body.Data != null)
{
if (200 == response.Body.Code)
{
Console.WriteLine("taskId: " + response.Body.Data.TaskId);
Console.WriteLine("liveId: " + response.Body.Data.LiveId);
Console.WriteLine("url: " + response.Body.Data.Url);
Console.WriteLine("sliceDetails: " + JsonConvert.SerializeObject(response.Body.Data.SliceDetails));
}
}
}
catch (TeaException error)
{
AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
}
catch (Exception _error)
{
TeaException error = new TeaException(new Dictionary<string, object>
{
{ "message", _error.Message }
});
AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
}
}
}
}
Detectar áudio local
Instalar as dependências
dotnet add package AlibabaCloud.SDK.Green20220302 --version 3.2.4
Instale o SDK do OSS via NuGet: pesquise por Aliyun.OSS.SDK (para .NET Framework) ou Aliyun.OSS.SDK.NetCore (para .NET Core) no NuGet Package Manager.
Para obter o código de exemplo completo em C# para moderação de áudio local, gere-o usando o OpenAPI Explorer.
Detectar áudio armazenado no OSS
Crie uma função de serviço na página Cloud Resource Access Authorization.
Instalar a dependência
dotnet add package AlibabaCloud.SDK.Green20220302 --version 3.2.4
Enviar uma tarefa de moderação
Para obter resultados, utilize o mesmo padrão VoiceModerationResultRequest descrito em Detectar áudio acessível publicamente.
Node.js SDK
Código-fonte: pacote npm.
O SDK oferece suporte a três cenários de moderação de áudio.
Detectar áudio acessível publicamente
Caso de uso
Quando o arquivo de áudio estiver acessível por uma URL pública, o Voice Moderation 2.0 recupera o arquivo via URL para moderação.
-
Execute o comando a seguir para instalar a dependência.
npm install @alicloud/green20220302@3.2.4 -
Utilize o SDK Node.js.
-
Código de exemplo para enviar uma tarefa de moderação de voz
const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: Reuse the client instance to avoid repeated connection creation. // If the project code is leaked, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. The following sample code is provided for reference only. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the environment variable is configured: ALIBABA_CLOUD_ACCESS_KEY_ID. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Make sure that the environment variable is configured: ALIBABA_CLOUD_ACCESS_KEY_SECRET. accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], endpoint: `green-cip.ap-southeast-1.aliyuncs.com`, }); return new Green20220302.default(config); } static async main() { const client = Client.createClient(); // Construct the request object const voiceModerationRequest = new Green20220302.VoiceModerationRequest({ // Voice moderation service code. "service": "audio_multilingual_global", // URL of the audio to moderate. "serviceParameters": JSON.stringify({"url":"http://aliyundoc.com/test.flv"}) }); // Create a runtime configuration object const runtime = new Util.RuntimeOptions(); try { // Send the request and get the response const response = await client.voiceModerationWithOptions(voiceModerationRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // This is for demonstration only. Handle exceptions properly in production. // Error message console.log('Error occurred:', error.message); } } } Client.main(); -
Código de exemplo para obter resultados de moderação de voz
const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: Reuse the client instance to avoid repeated connection creation. // If the project code is leaked, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. The following sample code is provided for reference only. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the environment variable is configured: ALIBABA_CLOUD_ACCESS_KEY_ID. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Make sure that the environment variable is configured: ALIBABA_CLOUD_ACCESS_KEY_SECRET. accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], endpoint: `green-cip.ap-southeast-1.aliyuncs.com`, }); return new Green20220302.default(config); } static async main() { const client = Client.createClient(); // Construct the request object const voiceModerationResultRequest = new Green20220302.VoiceModerationResultRequest({ // Voice moderation service code. "service": "audio_multilingual_global", "serviceParameters": JSON.stringify({"taskId":"<Task ID of the voice moderation result to query>"}) }); // Create a runtime configuration object const runtime = new Util.RuntimeOptions(); try { // Send the request and get the response const response = await client.voiceModerationResultWithOptions(voiceModerationResultRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // This is for demonstration only. Handle exceptions properly in production. // Error message console.log('Error occurred:', error.message); } } } Client.main();
-
Detectar áudio local
Caso de uso
Quando o arquivo de áudio estiver em uma máquina local sem URL pública, faça o upload dele para o bucket do OSS fornecido pelo Content Moderation. O Voice Moderation 2.0 acessa diretamente o OSS para recuperar o conteúdo de áudio para moderação.
-
Execute o comando a seguir para instalar a dependência.
npm install @alicloud/green20220302@3.2.4Instale o SDK do OSS:
npm install ali-oss --save -
Utilize o SDK Node.js.
-
Código de exemplo para enviar uma tarefa de moderação de voz
const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const { v4: uuidv4 } = require('uuid'); const OSS = require('ali-oss'); const Util = require('@alicloud/tea-util'); const path = require("path"); // Note: Reuse the client instance to avoid repeated connection creation. // If the project code is leaked, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. The following sample code is provided for reference only. //Whether the service is deployed on VPC var isVPC = false; //File upload token var tokenDic = new Array(); //File upload client var ossClient; //Set the endpoint var endpoint = 'green-cip.ap-southeast-1.aliyuncs.com' //Local file path var filePath = 'D:\\test\\voice\\cf02.wav' //Moderation service code var service = 'audio_multilingual_global' class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the environment variable is configured: ALIBABA_CLOUD_ACCESS_KEY_ID. accessKeyId: process.env["ALIBABA_CLOUD_ACCESS_KEY_ID"], // Required. Make sure that the environment variable is configured: ALIBABA_CLOUD_ACCESS_KEY_SECRET. accessKeySecret: process.env["ALIBABA_CLOUD_ACCESS_KEY_SECRET"], endpoint: endpoint, }); return new Green20220302.default(config); } // Create file upload client static getOssClient(tokenData, isVPC) { if (isVPC) { ossClient = new OSS({ accessKeyId: tokenData['accessKeyId'], accessKeySecret: tokenData['accessKeySecret'], stsToken: tokenData['securityToken'], endpoint: tokenData['ossInternalEndPoint'], bucket: tokenData['bucketName'], }); } else { ossClient = new OSS({ accessKeyId: tokenData['accessKeyId'], accessKeySecret: tokenData['accessKeySecret'], stsToken: tokenData['securityToken'], endpoint: tokenData['ossInternetEndPoint'], bucket: tokenData['bucketName'], }); } } static async main() { const client = Client.createClient(); // Create a runtime configuration object const runtime = new Util.RuntimeOptions(); //Get file upload token if (tokenDic[endpoint] == null || tokenDic[endpoint]['expiration'] <= Date.parse(new Date() / 1000)) { var tokenResponse = await client.describeUploadTokenWithOptions(runtime) tokenDic[endpoint] = tokenResponse.body.data; } //Get file upload client this.getOssClient(tokenDic[endpoint], isVPC) var split = filePath.split("."); var objectName; if (split.length > 1) { objectName = tokenDic[endpoint].fileNamePrefix + uuidv4() + "." + split[split.length - 1]; } else { objectName = tokenDic[endpoint].fileNamePrefix + uuidv4(); } //Upload file const result = await ossClient.put(objectName, path.normalize(filePath)); // Construct the request object const voiceModerationRequest = new Green20220302.VoiceModerationRequest({ // Moderation service code. "service": service, // URL of the audio to moderate. "serviceParameters": JSON.stringify({ "ossBucketName": tokenDic[endpoint].bucketName, "ossObjectName": objectName, }) }); try { // Send the request and get the response const response = await client.voiceModerationWithOptions(voiceModerationRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // This is for demonstration only. Handle exceptions properly in production. // Error message console.log('Error occurred:', error.message); } } } Client.main(); -
Código de exemplo para obter resultados de moderação de voz
const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: Reuse the client instance to avoid repeated connection creation. // If the project code is leaked, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. The following sample code is provided for reference only. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the environment variable is configured: ALIBABA_CLOUD_ACCESS_KEY_ID. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Make sure that the environment variable is configured: ALIBABA_CLOUD_ACCESS_KEY_SECRET. accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], endpoint: `green-cip.ap-southeast-1.aliyuncs.com`, }); return new Green20220302.default(config); } static async main() { const client = Client.createClient(); // Construct the request object const voiceModerationResultRequest = new Green20220302.VoiceModerationResultRequest({ // Voice moderation service code. "service": "audio_multilingual_global", "serviceParameters": JSON.stringify({"taskId":"<Task ID of the voice moderation result to query>"}) }); // Create a runtime configuration object const runtime = new Util.RuntimeOptions(); try { // Send the request and get the response const response = await client.voiceModerationResultWithOptions(voiceModerationResultRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // This is for demonstration only. Handle exceptions properly in production. // Error message console.log('Error occurred:', error.message); } } } Client.main();
-
Detectar áudio armazenado no OSS
Caso de uso
Se os arquivos de áudio estiverem armazenados no Alibaba Cloud OSS, autorize o serviço Content Moderation a acessar o OSS criando uma função de serviço. O Voice Moderation 2.0 acessa os arquivos do OSS para moderação por meio dessa função de serviço. Acesse a página Cloud Resource Access Authorization para criar uma função de serviço.
-
Execute o comando a seguir para instalar a dependência.
npm install @alicloud/green20220302@3.2.4 -
Utilize o SDK Node.js.
-
Código de exemplo para enviar uma tarefa de moderação de voz
const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: Reuse the client instance to avoid repeated connection creation. // If the project code is leaked, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. The following sample code is provided for reference only. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the environment variable is configured: ALIBABA_CLOUD_ACCESS_KEY_ID. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Make sure that the environment variable is configured: ALIBABA_CLOUD_ACCESS_KEY_SECRET. accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], endpoint: `green-cip.ap-southeast-1.aliyuncs.com`, }); return new Green20220302.default(config); } static async main() { const client = Client.createClient(); // Construct the request object const voiceModerationRequest = new Green20220302.VoiceModerationRequest({ // Voice moderation service code. "service": "audio_multilingual_global", "serviceParameters": JSON.stringify({ // Region of the bucket. Example: cn-shanghai "ossRegionId": "cn-shanghai", // Name of the bucket. Example: bucket001 "ossBucketName": "bucket001", // File to moderate. Example: voice/001.wav "ossObjectName": "voice/001.wav",}) }); }); // Create a runtime configuration object const runtime = new Util.RuntimeOptions(); try { // Send the request and get the response const response = await client.voiceModerationWithOptions(voiceModerationRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // This is for demonstration only. Handle exceptions properly in production. // Error message console.log('Error occurred:', error.message); } } } Client.main(); -
Código de exemplo para obter resultados de moderação de voz
const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: Reuse the client instance to avoid repeated connection creation. // If the project code is leaked, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. The following sample code is provided for reference only. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the environment variable is configured: ALIBABA_CLOUD_ACCESS_KEY_ID. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Make sure that the environment variable is configured: ALIBABA_CLOUD_ACCESS_KEY_SECRET. accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], endpoint: `green-cip.ap-southeast-1.aliyuncs.com`, }); return new Green20220302.default(config); } static async main() { const client = Client.createClient(); // Construct the request object const voiceModerationResultRequest = new Green20220302.VoiceModerationResultRequest({ // Voice moderation service code. "service": "audio_multilingual_global", "serviceParameters": JSON.stringify({"taskId":"<Task ID of the voice moderation result to query>"}) }); // Create a runtime configuration object const runtime = new Util.RuntimeOptions(); try { // Send the request and get the response const response = await client.voiceModerationResultWithOptions(voiceModerationResultRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // This is for demonstration only. Handle exceptions properly in production. // Error message console.log('Error occurred:', error.message); } } } Client.main();
-
Chamada nativa HTTPS
-
Call method
URL de solicitação do serviço: https://green-cip.{region}.aliyuncs.com
Protocolo: HTTPS
Método: POST
-
Common request parameters
Os parâmetros de entrada da API do Voice Moderation Enhanced Edition incluem parâmetros de solicitação comuns e parâmetros específicos da operação. Os parâmetros de solicitação comuns são obrigatórios em todas as chamadas de API. A tabela a seguir descreve esses parâmetros.
Nome
Tipo
Obrigatório
Descrição
Format
String
Sim
Formato da resposta. Valores válidos:
JSON (padrão)
XML
Version
String
Sim
Versão da API no formato AAAA-MM-DD. Versão atual: 2022-03-02.
AccessKeyId
String
Sim
O AccessKey ID emitido pela Alibaba Cloud para acessar serviços.
Signature
String
Sim
A string de assinatura. Para o método de cálculo, consulte a seção Mecanismo de assinatura abaixo.
SignatureMethod
String
Sim
O método de assinatura. Atualmente, apenas HMAC-SHA1 é suportado.
Timestamp
String
Sim
O carimbo de data/hora da solicitação. Especifique a hora no padrão ISO 8601 em UTC.
Formato: aaaa-MM-ddTHH:mm:ssZ.
Por exemplo, 2022-12-12T09:13:14 (UTC+8) é expresso como 2022-12-12T01:13:14Z.
SignatureVersion
String
Sim
Versão do algoritmo de assinatura. Valor fixo: 1.0.
SignatureNonce
String
Sim
Um número aleatório exclusivo para evitar ataques de repetição. Utilize um valor diferente para cada solicitação.
Action
String
Sim
Valores válidos:
VoiceModeration
VoiceModerationResult
-
Common response parameters
Para cada solicitação de API, independentemente de sucesso ou falha, o sistema retorna um identificador exclusivo (RequestId). Outros parâmetros de resposta variam dependendo do serviço chamado.
{ "RequestId":"20B935A9-XXXXXXXX-XXXXXXXX0C2", "Message":"SUCCESS", "Data":{ "TaskId":"au_f_O5xxxxxxxxxxxxxxqa-1****" }, "Code":200 } -
Code examples
Os exemplos de resposta a seguir estão formatados para facilitar a leitura. As respostas reais não são formatadas.
-
Exemplo de envio de tarefa de moderação
Exemplo de solicitação
http://green-cip.ap-southeast-1.aliyuncs.com/ ?Format=JSON &Version=2022-03-02 &Signature=vpEEL0zFHfxXYzSFV0n7%2FZiFL9o%3D &SignatureMethod=Hmac-SHA1 &SignatureNonce=15215528852396 &SignatureVersion=1.0 &Action=VoiceModeration &AccessKeyId=123****cip &Timestamp=2023-02-03T12:00:00Z &Service=audio_multilingual_global &ServiceParameters={"url": "https://xxxxxx.aliyuncs.com/sample/****.wav"}Exemplo de resposta
{ "RequestId":"20B935A9-XXXXXXXX-XXXXXXXX0C2", "Message":"SUCCESS", "Data":{ "TaskId":"au_f_O5xxxxxxxxxxxxxxqa-1x****" }, "Code":200 } -
Exemplo de consulta de resultado de tarefa
Exemplo de solicitação
http://green-cip.ap-southeast-1.aliyuncs.com/ ?Format=JSON &Version=2022-03-02 &Signature=vpEEL0zFHfxXYzSFV0n7%2FZiFL9o%3D &SignatureMethod=Hmac-SHA1 &SignatureNonce=15215528852396 &SignatureVersion=1.0 &Action=VoiceModerationResult &AccessKeyId=123****cip &Timestamp=2023-02-03T12:00:00Z &Service=audio_multilingual_global &ServiceParameters={"taskId": "au_f_O5zxxxxxxxxxxxxxxxx-1x****"}Exemplo de resposta
{ "RequestId":"926AD581-XXXXXXXXXXXXXX-7902AE", "Message":"success finished", "Data":{ "SliceDetails":[ { "EndTime":6, "StartTime":0, "Text":"The weather is nice today.", "Labels":"", "Url":"http://xxxx.aliyuncs.com/cip-media/voice/****.wav" } ] }, "Code":200 }
-
-
Signature mechanism
O Voice Moderation Enhanced Edition autentica todas as solicitações de acesso. Portanto, inclua informações de assinatura (Signature) em cada solicitação. O Voice Moderation Enhanced Edition utiliza criptografia simétrica com um AccessKey ID e AccessKey Secret para verificar a identidade do remetente da solicitação.
O AccessKey ID e o AccessKey Secret são emitidos pela Alibaba Cloud (você pode solicitá-los e gerenciá-los no site da Alibaba Cloud). O AccessKey ID identifica o visitante; o AccessKey Secret é a chave usada para criptografar e verificar a string de assinatura. Ele deve ser mantido em estrita confidencialidade.
Ao acessar o serviço, assine a solicitação da seguinte forma:
-
Construa uma string de consulta canônica usando os parâmetros da solicitação.
Ordene todos os parâmetros da solicitação em ordem alfabética (incluindo parâmetros de solicitação comuns e parâmetros específicos da operação, mas excluindo o próprio parâmetro Signature) em ordem lexicográfica.
-
Codifique os nomes e valores dos parâmetros em URL usando UTF-8.
NotaA maioria das bibliotecas de codificação de URL (como java.net.URLEncoder em Java) codifica com base no tipo MIME application/x-www-form-urlencoded. Utilize essa codificação e substitua os sinais de mais (+) por %20, asteriscos (*) por %2A e %7E de volta por tis (~) para obter a string codificada conforme descrito acima.
As regras de codificação de URL são as seguintes:
Os caracteres A-Z, a-z, 0-9, hifens (-), sublinhados (_), pontos (.) e tis (~) não são codificados.
Outros caracteres são codificados no formato
%XY, onde XY é a representação hexadecimal do código ASCII do caractere. Por exemplo, aspas duplas (") são codificadas como%22.Caracteres UTF-8 estendidos são codificados no formato
%XY%ZA….Observe que um caractere de espaço ( ) deve ser codificado como
%20, e não como sinais de mais (+).
Conecte cada nome de parâmetro codificado e seu valor com um sinal de igual (=).
Una os pares parâmetro=valor em ordem alfabética com um e comercial (&) para formar a string de consulta canônica.
-
Construa a string para cálculo de assinatura usando a string canônica da etapa a.i:
StringToSign= HTTPMethod + "&" + percentEncode ("/") + "&" + percentEncode (CanonicalizedQueryString)NotaOnde HTTPMethod é o método HTTP usado para enviar a solicitação, como POST. percentEncode(/) é o valor obtido pela codificação URL do caractere (/) de acordo com as regras de codificação URL descritas na etapa a.ii, que é
%2F. percentEncode(CanonicalQueryString) é a string obtida pela codificação URL da string de consulta canônica construída na etapa a.i de acordo com as regras de codificação URL descritas na etapa a.ii. -
Calcule o valor HMAC usando a string a ser assinada conforme definido na RFC 2104.
NotaNota: A chave usada para o cálculo da assinatura é o AccessKey Secret seguido por um caractere
&(ASCII: 38). O algoritmo de hash usado é SHA1. Codifique o valor HMAC usando Base64 para obter a Signature.
-
Adicione o valor da assinatura como o parâmetro Signature aos parâmetros da solicitação para concluir o processo de assinatura.
NotaAo enviar o valor da assinatura para o servidor Content Moderation como o parâmetro final da solicitação, codifique-o em URL de acordo com a RFC 3986, assim como os outros parâmetros.
-
Observações de uso
Reutilize instâncias de cliente. Criar um novo cliente para cada solicitação gera conexões desnecessárias. Inicialize um único cliente por endpoint e reutilize-o nas requisições.
Carregue credenciais a partir de variáveis de ambiente. Defina
ALIBABA_CLOUD_ACCESS_KEY_IDeALIBABA_CLOUD_ACCESS_KEY_SECRETcomo variáveis de ambiente. Não codifique valores de AccessKey diretamente no seu código.Expiração do token de upload. Tokens temporários obtidos via
DescribeUploadTokenpossuem validade limitada. Verifique o campoexpiratione renove o token antes que ele expire.Endpoints de VPC. Caso sua aplicação execute em uma VPC, utilize o endpoint de VPC (
green-cip-vpc.ap-southeast-1.aliyuncs.com) para evitar custos de tráfego de saída pela rede pública.