You can call Voice Moderation 2.0 using an SDK or by making native HTTPS requests. We recommend that you use an SDK to simplify the process because it handles tasks such as signature verification and request body construction. This topic describes how to access Voice Moderation 2.0.
Step 1: Activate the service
Go to the Activate Service page to activate the Voice Moderation Version 2.0 service. The default billing method is pay-as-you-go. After you integrate and use the API, you are automatically charged based on your usage. Daily fees are settled based on your actual usage. If you do not call the service, no fees are incurred.
After you activate the Content Moderation (Voice) Version 2.0 service, the default billing method is pay-as-you-go. This method bills you daily based on your actual usage. If you do not call the service, you will not be charged.
Step 2: Grant permissions to a RAM user
Before you can use an SDK or call an API operation, you must grant permissions to a Resource Access Management (RAM) user. You can create an AccessKey pair for your Alibaba Cloud account or a RAM user. When you call an Alibaba Cloud API operation, you must use an AccessKey pair to verify your identity. For more information, see Create an AccessKey pair.
Procedure
Log on to the RAM console as a RAM administrator.
- Create a RAM user.
For more information, see Create a RAM user.
- Grant the
AliyunYundunGreenWebFullAccesssystem policy to the RAM user.For more information, see Grant permissions to a RAM user.
After completing the preceding operations, you can call the Content Moderation API as the RAM user.
Step 3: Install and connect to the voice moderation service
The following table describes the supported regions.
Region | Public endpoint | VPC endpoint |
Singapore | green-cip.ap-southeast-1.aliyuncs.com | green-cip-vpc.ap-southeast-1.aliyuncs.com |
If you need SDK sample code in other programming languages, you can generate it using OpenAPI Explorer. OpenAPI Explorer dynamically generates sample code for the operation for different SDKs. The following API operations are available for online debugging:
In Alibaba Cloud SDK code, you can create a default access credential by defining ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables. When you call API operations of Alibaba Cloud services, the system directly accesses the credential, reads your AccessKey pair, and then automatically completes authentication. Before you use the SDK sample code, you must configure environment variables. For more information, see Configure credentials.
Java SDK
Java 1.8 or later is supported.
For more information about the source code, see Java SDK source code or Java SDK source code (OSS path).
The SDK supports the following three audio moderation scenarios.
Detecting publicly accessible audio
Scenarios
If an audio file for moderation is accessible from a public URL, the Audio Moderation Version 2.0 service can retrieve and moderate the file from the URL.
Add the following dependency to the dependencies file:
<dependency> <groupId>com.aliyun</groupId> <artifactId>green20220302</artifactId> <version>2.2.11</version> </dependency>Use the Java SDK.
Sample code for submitting a voice moderation task
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 VoiceModerationDemo { 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("url", "https://xxxx/xxx/sample.wav"); VoiceModerationRequest voiceModerationRequest = new VoiceModerationRequest(); // Moderation type: audio_multilingual_global for multi-language audio moderation. voiceModerationRequest.setService("audio_multilingual_global"); 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(); } } }Sample code for querying the result of a voice moderation task
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(); } } }
Detecting local audio
Scenarios
If the audio that you need to moderate is stored on a local machine and does not have a public URL, you can upload the audio to an Object Storage Service (OSS) bucket provided by Content Moderation. The Audio Moderation Version 2.0 service can then directly access OSS to retrieve and moderate the audio content.
Add the following dependency to the dependencies file:
<dependency> <groupId>com.aliyun</groupId> <artifactId>green20220302</artifactId> <version>2.2.11</version> </dependency>Install the OSS SDK:
<dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.16.3</version> </dependency>Use the Java SDK.
Sample code for submitting a voice moderation task
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(); } } }Speech detection task: Code example
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(); } } }
Moderate audio files in OSS
Scenarios
If the audio files that you need to moderate are already stored in Alibaba Cloud Object Storage Service (OSS), you can create a service role to grant the Content Moderation service access to OSS. The Audio Moderation Version 2.0 service then uses the service role to retrieve and moderate files from OSS. To create the service role, go to the Cloud Resource Access Authorization page.
Add the following dependency to the dependencies file:
<dependency> <groupId>com.aliyun</groupId> <artifactId>green20220302</artifactId> <version>2.2.11</version> </dependency>Use the Java SDK.
Sample code for submitting a voice moderation task
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(); } } }You can obtain a code sample for a speech detection task.
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(); } } }
Python SDK
Python 3.6 or later is supported.
For more information about the source code, see Python SDK source code.
The SDK supports the following three audio moderation scenarios.
Detecting publicly accessible audio
Scenarios
If an audio file for moderation is accessible from a public URL, the Audio Moderation V2.0 service can retrieve and moderate the file from the URL.
Run the following command to install the dependencies:
pip install alibabacloud_green20220302==2.2.11Use the Python SDK.
Sample code for submitting a voice moderation task
# coding=utf-8 # python version >= 3.6 from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config import json config = 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.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Obtain the AccessKey secret of your RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id='We recommend that you obtain the AccessKey ID of your RAM user from an environment variable', access_key_secret='We recommend that you obtain the AccessKey secret of your RAM user from an environment variable', # The connection timeout period in milliseconds (ms). connect_timeout=10000, # The read timeout period in milliseconds (ms). read_timeout=3000, region_id='ap-southeast-1', endpoint='green-cip.ap-southeast-1.aliyuncs.com' ) # Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation. clt = Client(config) serviceParameters = { 'url': 'https://xxxx/xxx/sample.wav', } voiceModerationRequest = models.VoiceModerationRequest( # Moderation type: audio_multilingual_global for multi-language audio moderation. service='audio_multilingual_global', service_parameters=json.dumps(serviceParameters) ) try: response = clt.voice_moderation(voiceModerationRequest) if response.status_code == 200: # The call was successful. # Obtain the moderation result. result = response.body print('response success. result:{}'.format(result)) else: print('response not success. status:{} ,result:{}'.format(response.status_code, response)) except Exception as err: print(err)Retrieving the results of a voice detection task
# coding=utf-8 # python version >= 3.6 from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config import json config = 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.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Obtain the AccessKey secret of your RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id='We recommend that you obtain the AccessKey ID of your RAM user from an environment variable', access_key_secret='We recommend that you obtain the AccessKey secret of your RAM user from an environment variable', # The connection timeout period in milliseconds (ms). connect_timeout=10000, # The read timeout period in milliseconds (ms). read_timeout=3000, region_id='ap-southeast-1', endpoint='green-cip.ap-southeast-1.aliyuncs.com' ) # Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation. clt = Client(config) # The taskId returned when the task was submitted. serviceParameters = { "taskId": 'The task ID returned for the moderation task' } voiceModerationResultRequest = models.VoiceModerationResultRequest( # Moderation type: audio_multilingual_global for multi-language audio moderation. service='audio_multilingual_global', service_parameters=json.dumps(serviceParameters) ) try: response = clt.voice_moderation_result(voiceModerationResultRequest) if response.status_code == 200: # The call was successful. # Obtain the moderation result. result = response.body print('response success. result:{}'.format(result)) else: print('response not success. status:{} ,result:{}'.format(response.status_code, response)) except Exception as err: print(err)Cancel a live stream detection Job
Detecting local audio
Scenarios
If the audio that you need to moderate is stored on a local machine and does not have a public URL, you can upload the audio to an Object Storage Service (OSS) bucket provided by Content Moderation. The Audio Moderation Version 2.0 service can then directly access OSS to retrieve the audio content for moderation.
Run the following command to install the dependencies:
pip install alibabacloud_green20220302==2.2.11Install the OSS SDK:
pip install oss2Use the Python SDK.
Sample code for submitting a voice moderation task
# coding=utf-8 # python version >= 3.6 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 import json import uuid import oss2 import time import os # Specifies whether the service is deployed in a VPC. is_vpc = False # The token used to upload the file. The key is the endpoint and the value is the token. token_dict = dict() # The client used to upload the file. bucket = None # Create a client. def create_client(access_key_id, access_key_secret, endpoint): config = Config( access_key_id=access_key_id, access_key_secret=access_key_secret, # Set an HTTP proxy. # http_proxy='http://10.10.xx.xx:xxxx', # Set an HTTPS proxy. # https_proxy='https://10.10.xx.xx:xxxx', # Modify the endpoint as needed. endpoint=endpoint ) return Client(config) # Create a client to upload a file. def create_oss_bucket(is_vpc, upload_token): global token_dict global bucket auth = oss2.StsAuth(upload_token.access_key_id, upload_token.access_key_secret, upload_token.security_token) if (is_vpc): end_point = upload_token.oss_internal_end_point else: end_point = upload_token.oss_internet_end_point # Note: To improve moderation performance, reuse the bucket instance. This avoids repeated connection creation. bucket = oss2.Bucket(auth, end_point, upload_token.bucket_name) # Upload a file. def upload_file(file_name, upload_token): create_oss_bucket(is_vpc, upload_token) object_name = upload_token.file_name_prefix + str(uuid.uuid1()) + '.' + file_name.split('.')[-1] bucket.put_object_from_file(object_name, file_name) return object_name def invoke_function(access_key_id, access_key_secret, endpoint): # Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation. client = create_client(access_key_id, access_key_secret, endpoint) # Create a RuntimeObject instance and set runtime parameters. runtime = util_models.RuntimeOptions() # The full path of the local file. Example: D:\localPath\exampleFile.mp3 file_path = 'D:\localPath\exampleFile.mp3' # Obtain a temporary token to upload the file. upload_token = token_dict.setdefault(endpoint, None) if (upload_token == None) or int(upload_token.expiration) <= int(time.time()): response = client.describe_upload_token() upload_token = response.body.data token_dict[endpoint] = upload_token # Upload the file. object_name = upload_file(file_path, upload_token) # Construct moderation parameters. service_parameters = { # The name of the bucket in which the file to be moderated is stored. 'ossBucketName': upload_token.bucket_name, # The file to be moderated. 'ossObjectName': object_name, # The unique ID of the data. 'dataId': str(uuid.uuid4()) } voice_moderation_request = models.VoiceModerationRequest( # The audio moderation service. The value is the service code that is configured for the rule in the Voice Moderation 2.0 console. Example: audio_multilingual_global. service='audio_multilingual_global', service_parameters=json.dumps(service_parameters) ) try: return client.voice_moderation_with_options(voice_moderation_request, runtime) except Exception as err: print(err) if __name__ == '__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.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Obtain the AccessKey secret of your RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id = 'We recommend that you obtain the AccessKey ID of your RAM user from an environment variable' access_key_secret = 'We recommend that you obtain the AccessKey secret of your RAM user from an environment variable' # Modify the region and endpoint as needed. response = invoke_function(access_key_id, access_key_secret, 'green-cip.ap-southeast-1.aliyuncs.com') if response.status_code == 200: # The call was successful. # Obtain the moderation result. result = response.body print('response success. result:{}'.format(result)) if result.code == 200: result_data = result.data print('result: {}'.format(result_data)) else: print('response not success. status:{} ,result:{}'.format(response.status_code, response))Obtain the results of a speech detection job
# coding=utf-8 # python version >= 3.6 from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config import json config = 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.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Obtain the AccessKey secret of your RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id='We recommend that you obtain the AccessKey ID of your RAM user from an environment variable', access_key_secret='We recommend that you obtain the AccessKey secret of your RAM user from an environment variable', # The connection timeout period in milliseconds (ms). connect_timeout=10000, # The read timeout period in milliseconds (ms). read_timeout=3000, region_id='ap-southeast-1', endpoint='green-cip.ap-southeast-1.aliyuncs.com' ) # Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation. clt = Client(config) # The taskId returned when the task was submitted. serviceParameters = { "taskId": 'The task ID returned for the moderation task' } voiceModerationResultRequest = models.VoiceModerationResultRequest( # Moderation type: audio_multilingual_global for multi-language audio moderation. service='audio_multilingual_global', service_parameters=json.dumps(serviceParameters) ) try: response = clt.voice_moderation_result(voiceModerationResultRequest) if response.status_code == 200: # The call was successful. # Obtain the moderation result. result = response.body print('response success. result:{}'.format(result)) else: print('response not success. status:{} ,result:{}'.format(response.status_code, response)) except Exception as err: print(err)
Moderate audio files in OSS
Scenarios
If the audio files that you need to moderate are stored in Alibaba Cloud Object Storage Service (OSS), you can create a service role to grant the Content Moderation service access to OSS. The Audio ModerationV2.0 service then uses the service role to retrieve files from OSS for moderation. To create a service role, visit the Cloud Resource Access Authorization page.
Run the following command to install the dependencies:
pip install alibabacloud_green20220302==2.2.11Use the Python SDK.
Sample code for submitting a voice moderation task
# coding=utf-8 # python version >= 3.6 from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config import json config = 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.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Obtain the AccessKey secret of your RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id='We recommend that you obtain the AccessKey ID of your RAM user from an environment variable', access_key_secret='We recommend that you obtain the AccessKey secret of your RAM user from an environment variable', # The connection timeout period in milliseconds (ms). connect_timeout=10000, # The read timeout period in milliseconds (ms). read_timeout=3000, region_id='ap-southeast-1', endpoint='green-cip.ap-southeast-1.aliyuncs.com' ) # Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation. clt = Client(config) serviceParameters = { 'ossBucketName': 'bucket_01', 'ossObjectName': 'test/test.mp3', 'ossRegionId': 'cn-shanghai' } voiceModerationRequest = models.VoiceModerationRequest( # Moderation type: audio_multilingual_global for multi-language audio moderation. service='audio_multilingual_global', service_parameters=json.dumps(serviceParameters) ) try: response = clt.voice_moderation(voiceModerationRequest) if response.status_code == 200: # The call was successful. # Obtain the moderation result. result = response.body print('response success. result:{}'.format(result)) else: print('response not success. status:{} ,result:{}'.format(response.status_code, response)) except Exception as err: print(err)Retrieve the results of a speech detection task
# coding=utf-8 # python version >= 3.6 from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config import json config = 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.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Obtain the AccessKey secret of your RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id='We recommend that you obtain the AccessKey ID of your RAM user from an environment variable', access_key_secret='We recommend that you obtain the AccessKey secret of your RAM user from an environment variable', # The connection timeout period in milliseconds (ms). connect_timeout=10000, # The read timeout period in milliseconds (ms). read_timeout=3000, region_id='ap-southeast-1', endpoint='green-cip.ap-southeast-1.aliyuncs.com' ) # Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation. clt = Client(config) # The taskId returned when the task was submitted. serviceParameters = { "taskId": 'The task ID returned for the moderation task' } voiceModerationResultRequest = models.VoiceModerationResultRequest( # Moderation type: audio_multilingual_global for multi-language audio moderation. service='audio_multilingual_global', service_parameters=json.dumps(serviceParameters) ) try: response = clt.voice_moderation_result(voiceModerationResultRequest) if response.status_code == 200: # The call was successful. # Obtain the moderation result. result = response.body print('response success. result:{}'.format(result)) else: print('response not success. status:{} ,result:{}'.format(response.status_code, response)) except Exception as err: print(err)Canceling a live stream moderation task
PHP SDK
PHP 5.6 or later is supported.
For more information about the source code, see PHP SDK source code.
The SDK supports the following three audio moderation scenarios.
Scan publicly accessible audio
Scenarios
If an audio file for moderation is accessible from a public URL, the Audio Moderation Version 2.0 service can retrieve the file from the URL for moderation.
Run the following command to install the dependencies:
composer require alibabacloud/green-20220302 2.2.10Use the PHP SDK.
Sample code for submitting a voice moderation task
<?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('url' => 'https://xxxx/xxx/sample.wav'); $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()); }Sample code for querying the result of a voice moderation task
<?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("riskLevel = " . $data->riskLevel); 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()); }
Detecting local audio
Scenarios
To moderate an audio file that is on a local machine and does not have a public URL, you can upload the file to an Object Storage Service (OSS) bucket provided by Content Moderation. The Audio Moderation Version 2.0 service can then directly access OSS to retrieve the audio content for moderation.
Run the following command to install the dependencies:
composer require alibabacloud/green-20220302 2.2.10Install the OSS SDK:
composer require aliyuncs/oss-sdk-phpUse the PHP SDK.
Sample code for submitting a voice moderation task
<?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()); }Sample code for querying the result of a voice moderation task
<?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()); }
Moderate audio files in OSS
Scenarios
To moderate audio files stored in Alibaba Cloud Object Storage Service (OSS), you can create a service role to grant the Content Moderation service access to OSS. The Audio Moderation V2.0 service uses this service role to retrieve and moderate files from OSS. To create the service role, visit the Cloud Resource Access Authorization page.
Run the following command to install the dependencies:
composer require alibabacloud/green-20220302 2.2.10Use the PHP SDK.
Sample code for submitting a voice moderation task
<?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()); }Sample code for querying the result of a voice moderation task
<?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()); }
Go SDK
The SDK supports the following three audio moderation scenarios.
Detecting publicly accessible audio
Scenarios
If an audio file for moderation is accessible from a public URL, the Audio Moderation Version 2.0 service can retrieve the file from the URL for moderation.
Run the following command to install the dependencies:
go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2Use the Go SDK.
Sample code for submitting a voice moderation task
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{}{ "url": "https://xxxx/xxx/sample.wav", }, ) 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)) } }Sample code for querying the result of a voice moderation task
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)) } }
Detecting local audio
Scenarios
If the audio that you need to moderate is stored on a local machine and does not have a public URL, you can upload the audio to an Object Storage Service (OSS) bucket provided by Content Moderation. The Audio Moderation 2.0 service can then directly access OSS to retrieve the audio content for moderation.
Run the following command to install the dependencies:
go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2Install the OSS SDK:
go get github.com/aliyun/aliyun-oss-go-sdk/ossUse the Go SDK.
Sample code for submitting a voice moderation task
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)) } } }Sample code for querying the result of a voice moderation task
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)) } }
Moderate audio files in OSS
Scenarios
If the audio files that you need to moderate are already stored in Alibaba Cloud Object Storage Service (OSS), you can create a service role to grant the Content Moderation service access to OSS. The Audio Moderation Version 2.0 service retrieves files from OSS using the service role to perform moderation. To create a service role, visit the Cloud Resource Access Authorization page.
Run the following command to install the dependencies:
go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2Use the Go SDK.
Sample code for submitting a voice moderation task
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)) } }Sample code for querying the result of a voice moderation task
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)) } }
C# SDK
For more information about the source code, see C# SDK source code.
The SDK supports the following three audio moderation scenarios.
Moderate publicly accessible audio files
Scenarios
If an audio file for moderation is accessible from a public URL, the Audio Moderation Version 2.0 service can retrieve the file from the URL for moderation.
Run the following command to install the dependencies:
dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.10Use the C# SDK.
Sample code for submitting a voice moderation task
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>(); // The URL of the audio file to moderate. The URL must be publicly accessible. task.Add("url","https://xxxx/xxx/sample.wav"); 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); } } } }Sample code for querying the result of a voice moderation task
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); } } } }
Detecting local audio
Scenarios
If the audio that you need to moderate is stored on a local machine and does not have a public URL, you can upload the audio to an Object Storage Service (OSS) bucket provided by Content Moderation. The Audio Moderation 2.0 service can then directly access OSS to retrieve the audio content for moderation.
Run the following command to install the dependencies:
dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.10Install the OSS SDK:
Install using NuGet 1. If NuGet is not installed in your Visual Studio, install NuGet. 2. In Visual Studio, create or open a project. Choose Tools > NuGet Package Manager > Manage NuGet Packages for Solution. 3. Search for aliyun.oss.sdk. In the results, find Aliyun.OSS.SDK (for .NET Framework) or Aliyun.OSS.SDK.NetCore (for .NET Core). Select the latest version and click Install.Use the C# SDK.
Sample code for submitting a voice moderation task
// This file is auto-generated, don't edit it. Thanks. using System; using Newtonsoft.Json; using Aliyun.OSS; namespace AlibabaCloud.SDK.Green20220302 { public class VoiceModerationAutoRoute { //The token used to upload the file. public static Dictionary<String, Models.DescribeUploadTokenResponse> tokenDic = new Dictionary<String, Models.DescribeUploadTokenResponse>(); //The client used to upload the file. public static OssClient ossClient = null; //Specifies whether the service is deployed in a VPC. public static Boolean isVPC = false; public static void Main(string[] args) { /** * 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"; // Modify the region and endpoint as needed. String endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; Models.VoiceModerationResponse response = invoke( accessKeyId, accessKeySecret, endpoint ); //Automatic routing. The region is switched to ap-southeast-1. if ( response is null || response.Body is null || AlibabaCloud.TeaUtil.Common.EqualNumber( 500, AlibabaCloud.TeaUtil.Common.AssertAsNumber(response.StatusCode) ) || AlibabaCloud.TeaUtil.Common.EqualString( "500", Convert.ToString(response.Body.Code) ) ) { endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; response = invoke(accessKeyId, accessKeySecret, endpoint); ; } Console.WriteLine(response.Body.RequestId); Console.WriteLine(JsonConvert.SerializeObject(response.Body)); } //Create a client. public static Client createClient( String accessKeyId, String accessKeySecret, String endpoint ) { AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, //Set an HTTP proxy. //HttpProxy = "http://10.10.xx.xx:xxxx", //Set an HTTPS proxy. //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999", //The endpoint of the service. Endpoint = endpoint, }; return new Client(config); } //Create a client to upload a file. private static OssClient getOssClient( Models.DescribeUploadTokenResponse tokenResponse, Boolean isVPC ) { var tokenData = tokenResponse.Body.Data; if (isVPC) { return new OssClient( tokenData.OssInternalEndPoint, tokenData.AccessKeyId, tokenData.AccessKeySecret, tokenData.SecurityToken ); } else { return new OssClient( tokenData.OssInternetEndPoint, tokenData.AccessKeyId, tokenData.AccessKeySecret, tokenData.SecurityToken ); } } //Upload a file. public static String uploadFile( String filePath, Models.DescribeUploadTokenResponse tokenResponse ) { // Create an OssClient instance. ossClient = getOssClient(tokenResponse, isVPC); var tokenData = tokenResponse.Body.Data; String objectName = tokenData.FileNamePrefix + Guid.NewGuid().ToString() + "." + filePath.Split(".").GetValue(1); //Upload the file. ossClient.PutObject(tokenData.BucketName, objectName, filePath); return objectName; } //Submit a moderation request. public static Models.VoiceModerationResponse invoke( String accessKeyId, String accessKeySecret, String endpoint ) { //Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation. Client client = createClient(accessKeyId, accessKeySecret, endpoint); //Set runtime parameters. The settings take effect only on requests that use this runtime parameter instance. AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); //The full path of the local file. Example: D:\localPath\exampleFile.wav. String filePath = "D:\localPath\exampleFile.wav"; try { //Obtain a temporary token to upload the file. if ( !tokenDic.ContainsKey(endpoint) || tokenDic[endpoint].Body.Data.Expiration <= DateTimeOffset.Now.ToUnixTimeSeconds() ) { var tokenResponse = client.DescribeUploadToken(); tokenDic[endpoint] = tokenResponse; } //Upload the file. String objectName = uploadFile(filePath, tokenDic[endpoint]); //Construct a voice moderation request. Models.VoiceModerationRequest voiceModerationRequest = new Models.VoiceModerationRequest(); //The voice moderation service. Example: audio_multilingual_global. voiceModerationRequest.Service = "audio_multilingual_global"; Dictionary<string, object> task = new Dictionary<string, object>(); //The information about the audio file to be moderated. task.Add("ossBucketName", tokenDic[endpoint].Body.Data.BucketName); task.Add("ossObjectName", objectName); //The ID of the data to be moderated. task.Add("dataId", Guid.NewGuid().ToString()); voiceModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task); //Call the API operation to query the moderation result. Models.VoiceModerationResponse response = client.VoiceModerationWithOptions( voiceModerationRequest, runtimeOptions ); return response; } catch (Exception _err) { Console.WriteLine(_err); return null; } } } }Sample code for querying the result of a voice moderation task
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); } } } }
Moderate audio files in OSS
Scenarios
If the audio files that you need to moderate are stored in Alibaba Cloud Object Storage Service (OSS), you can create a service role to grant the Content Moderation service access to OSS. The Audio Moderation Version 2.0 service uses this service role to retrieve files from OSS for moderation. To create the service role, visit the Cloud Resource Access Authorization page.
Run the following command to install the dependencies:
dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.10Use the C# SDK.
Sample code for submitting a voice moderation task
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); } } } }Sample code for querying the result of a voice moderation task
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); } } } }
Node.js SDK
For more information about the source code, see Node.js SDK source code.
The SDK supports the following three audio moderation scenarios.
Moderate publicly accessible audio files
Scenarios
If an audio file for moderation is accessible from a public URL, the Audio Moderation Version 2.0 service can retrieve the file from the URL for moderation.
Run the following command to install the dependencies:
npm install @alicloud/green20220302@2.2.10Use the Node.js SDK.
Sample code for submitting a voice moderation task
const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation. // 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. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured. 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 a request object. const voiceModerationRequest = new Green20220302.VoiceModerationRequest({ // The voice moderation service. "service": "audio_multilingual_global", // The URL of the audio file 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 obtain the response. const response = await client.voiceModerationWithOptions(voiceModerationRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // This section is for printing only. Handle exceptions with caution in your project. Do not ignore exceptions. // Error message console.log('Error occurred:', error.message); } } } Client.main();Sample code for querying the result of a voice moderation task
const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation. // 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. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured. 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 a request object. const voiceModerationResultRequest = new Green20220302.VoiceModerationResultRequest({ // The voice moderation service. "service": "audio_multilingual_global", "serviceParameters": JSON.stringify({"taskId":"<The ID of the task whose moderation result you want to query>"}) }); // Create a runtime configuration object. const runtime = new Util.RuntimeOptions(); try { // Send the request and obtain the response. const response = await client.voiceModerationResultWithOptions(voiceModerationResultRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // This section is for printing only. Handle exceptions with caution in your project. Do not ignore exceptions. // Error message console.log('Error occurred:', error.message); } } } Client.main();
Detecting local audio
Scenarios
If the audio that you need to moderate is stored on a local machine and does not have a public URL, you can upload the audio to an Object Storage Service (OSS) bucket provided by Content Moderation. This allows the Audio Moderation Version 2.0 service to directly access OSS, retrieve the audio content, and perform moderation.
Run the following command to install the dependencies:
npm install @alicloud/green20220302@2.2.10Install the OSS SDK:
npm install ali-oss --saveUse the Node.js SDK.
Sample code for submitting a voice moderation task
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: To improve moderation performance, reuse the client instance. This avoids repeated connection creation. // 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. //Specifies whether the service is deployed in a VPC. var isVPC = false; //The token used to upload the file. var tokenDic = new Array(); //The client used to upload the file. var ossClient; //Set the endpoint. var endpoint = 'green-cip.ap-southeast-1.aliyuncs.com' //The path of the local file. var filePath = 'D:\\test\\voice\\cf02.wav' //The moderation service. var service = 'audio_multilingual_global' class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured. accessKeyId: "We recommend that you obtain the AccessKey ID of your RAM user from an environment variable", // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured. accessKeySecret: "We recommend that you obtain the AccessKey secret of your RAM user from an environment variable", endpoint: endpoint, }); return new Green20220302.default(config); } //Create a client to upload a file. 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(); //Obtain a temporary token to upload the file. if (tokenDic[endpoint] == null || tokenDic[endpoint]['expiration'] <= Date.parse(new Date() / 1000)) { var tokenResponse = await client.describeUploadTokenWithOptions(runtime) tokenDic[endpoint] = tokenResponse.body.data; } //Obtain the client used to upload the file. 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 the file. const result = await ossClient.put(objectName, path.normalize(filePath)); // Construct a request object. const voiceModerationRequest = new Green20220302.VoiceModerationRequest({ // The moderation service. "service": service, // The URL to be moderated. "serviceParameters": JSON.stringify({ "ossBucketName": tokenDic[endpoint].bucketName, "ossObjectName": objectName, }) }); try { // Send the request and obtain the response. const response = await client.voiceModerationWithOptions(voiceModerationRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // This section is for printing only. Handle exceptions with caution in your project. Do not ignore exceptions. // Error message console.log('Error occurred:', error.message); } } } Client.main();Sample code for querying the result of a voice moderation task
const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation. // 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. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured. 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 a request object. const voiceModerationResultRequest = new Green20220302.VoiceModerationResultRequest({ // The voice moderation service. "service": "audio_multilingual_global", "serviceParameters": JSON.stringify({"taskId":"<The ID of the task whose moderation result you want to query>"}) }); // Create a runtime configuration object. const runtime = new Util.RuntimeOptions(); try { // Send the request and obtain the response. const response = await client.voiceModerationResultWithOptions(voiceModerationResultRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // This section is for printing only. Handle exceptions with caution in your project. Do not ignore exceptions. // Error message console.log('Error occurred:', error.message); } } } Client.main();
Moderate audio files in OSS
Scenarios
If the audio files that you need to moderate are already stored in Alibaba Cloud Object Storage Service (OSS), you can create a service role to grant the Content Moderation service access to OSS. The Audio Moderation V2.0 service uses the service role to retrieve files from OSS for moderation. To create the service role, visit the Cloud Resource Access Authorization page.
Run the following command to install the dependencies:
npm install @alicloud/green20220302@2.2.10Use the Node.js SDK.
Sample code for submitting a voice moderation task
const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation. // 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. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured. 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 a request object. const voiceModerationRequest = new Green20220302.VoiceModerationRequest({ // The voice moderation service. "service": "audio_multilingual_global", "serviceParameters": JSON.stringify({ // The region where the bucket that stores 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 file to be moderated. Example: voice/001.wav "ossObjectName": "voice/001.wav",}) }); }); // Create a runtime configuration object. const runtime = new Util.RuntimeOptions(); try { // Send the request and obtain the response. const response = await client.voiceModerationWithOptions(voiceModerationRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // This section is for printing only. Handle exceptions with caution in your project. Do not ignore exceptions. // Error message console.log('Error occurred:', error.message); } } } Client.main();Sample code for querying the result of a voice moderation task
const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: To improve moderation performance, reuse the client instance. This avoids repeated connection creation. // 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. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured. 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 a request object. const voiceModerationResultRequest = new Green20220302.VoiceModerationResultRequest({ // The voice moderation service. "service": "audio_multilingual_global", "serviceParameters": JSON.stringify({"taskId":"<The ID of the task whose moderation result you want to query>"}) }); // Create a runtime configuration object. const runtime = new Util.RuntimeOptions(); try { // Send the request and obtain the response. const response = await client.voiceModerationResultWithOptions(voiceModerationResultRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // This section is for printing only. Handle exceptions with caution in your project. Do not ignore exceptions. // Error message console.log('Error occurred:', error.message); } } } Client.main();
Native HTTPS calls
Request method
Service request URL: https://green-cip.{region}.aliyuncs.com
Protocol: HTTPS
Method: POST
Common request parameters
Requests to Voice Moderation 2.0 API operations include common request parameters and operation-specific request parameters. Common request parameters are required for every API operation and are described in the following table.
Name
Type
Required
Description
Format
String
Yes
The format of the response. Valid values:
JSON (default)
XML
Version
String
Yes
The version of the API. The value is in the YYYY-MM-DD format. Set the value to 2022-03-02.
AccessKeyId
String
Yes
The AccessKey ID provided by Alibaba Cloud.
Signature
String
Yes
The signature string of the request. For more information about how to calculate a signature, see the Signature method section of this topic.
SignatureMethod
String
Yes
The signature method. HMAC-SHA1 is supported.
Timestamp
String
Yes
The timestamp of the request. The time follows the ISO 8601 standard and must be in UTC.
The format is yyyy-MM-ddTHH:mm:ssZ.
For example, 09:13:14 on December 12, 2022 (UTC+8) is represented as 2022-12-12T01:13:14Z.
SignatureVersion
String
Yes
The version of the signature algorithm. Set the value to 1.0.
SignatureNonce
String
Yes
A unique random number used to prevent replay attacks. You must use a different random number for each request.
Action
String
Yes
Valid values:
VoiceModeration
VoiceModerationResult
Common response parameters
The system returns a unique RequestId for each API request, regardless of whether the call is successful. Other response parameters vary depending on the API operation.
{ "RequestId":"20B935A9-XXXXXXXX-XXXXXXXX0C2", "Message":"SUCCESS", "Data":{ "TaskId":"au_f_O5xxxxxxxxxxxxxxqa-1****" }, "Code":200 }Code examples
The following sample responses are formatted to improve readability. Actual responses are not formatted with line breaks or indentation.
Sample moderation task
Sample request
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"}Sample success response
{ "RequestId":"20B935A9-XXXXXXXX-XXXXXXXX0C2", "Message":"SUCCESS", "Data":{ "TaskId":"au_f_O5xxxxxxxxxxxxxxqa-1x****" }, "Code":200 }Sample query task
Sample request
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****"}Sample success response
{ "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 method
The Voice Moderation 2.0 service authenticates each access request. Therefore, you must include signature information in each request. Voice Moderation 2.0 uses symmetric encryption with an AccessKey pair to authenticate the request sender.
An AccessKey pair, which consists of an AccessKey ID and an AccessKey secret, is issued by Alibaba Cloud. You can apply for and manage it on the Alibaba Cloud website. The AccessKey ID is used to verify the identity of the user, and the AccessKey secret is used to encrypt and verify the signature string. You must keep your AccessKey secret confidential.
To sign a request, perform the following steps:
Create a canonicalized query string.
Sort all request parameters, including common and operation-specific parameters but not the Signature parameter, in alphabetical order by parameter name.
Encode the names and values of the request parameters. Parameter names and values must be URL-encoded using the UTF-8 character set.
NoteMost libraries that support URL encoding, such as
java.net.URLEncoderin Java, encode data according to theapplication/x-www-form-urlencodedMIME type. To produce an encoded string that conforms to the preceding rules, you can use this encoding method and then make the following replacements in the output string: replace the plus sign (+) with %20, the asterisk (*) with %2A, and %7E with a tilde (~).The URL encoding rules are as follows:
Uppercase letters, lowercase letters, digits, and special characters such as hyphens (-), underscores (_), periods (.), and tildes (~) are not encoded.
Other characters are encoded in the
%XYformat, where XY represents the hexadecimal ASCII code of the character. For example, double quotation marks (") are encoded as%22.Extended UTF-8 characters are encoded in the
%XY%ZA…format.Spaces are encoded as
%20, not plus signs (+).
Connect the encoded parameter names and values with equal signs (=).
Connect the key-value pairs with ampersands (&) to create the canonicalized query string.
Construct the string to sign using the canonicalized string from step a.i according to the following rules:
StringToSign= HTTPMethod + "&" + percentEncode("/") + "&" + percentEncode(CanonicalizedQueryString)NoteHTTPMethod is the HTTP method of the request, such as POST. percentEncode("/") is the encoded value of the forward slash (/) character, according to the URL encoding rules described in Step 1.b. The encoded value is
%2F. percentEncode(CanonicalizedQueryString) is the encoded string of the canonicalized query string from Step 1.d, according to the URL encoding rules described in Step 1.b.Calculate the HMAC value of the string-to-sign according to RFC 2104.
NoteThe key used to calculate the signature is your AccessKey secret appended with an ampersand (
&) character (ASCII code 38). The SHA1 hash algorithm is used.Encode the HMAC value in Base64 to create the signature string.
Add the signature string to the request as the Signature parameter.
NoteThe Signature value must be URL-encoded according to RFC 3986 before you add it to the request.