You can call the Voice Moderation 2.0 API by using SDKs or HTTPS requests. We recommend that you use SDKs to call the API so as to skip some operations such as signature verification and HTTPS request body construction. This topic describes how to use Voice Moderation 2.0.
Step 1: Activate Voice Moderation 2.0
Open the service activation page and activate the Voice Moderation 2.0 service. After you call API operations, the billing system automatically charges you based on your usage.
After you activate the Voice Moderation 2.0service, the default billing method is pay-as-you-go. Daily fees are calculated based on the actual usage. If the service is not called, no charge is made.
Step 2: Grant permissions to a RAM user
Before you call API operations or use SDKs as a Resource Access Management (RAM) user, you must grant permissions to the RAM user. You can create an AccessKey pair for your Alibaba Cloud account and the RAM user. When you call API operations, you must use the AccessKey pair to complete identity verification. For information about how to obtain an AccessKey pair, see Obtain 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
AliyunYundunGreenWebFullAccess
system 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 SDKs and use the SDKs to call the Voice Moderation 2.0 service
The following table provides the supported regions.
Region | Public endpoint | Internal 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 call an API operation in OpenAPI Explorer. OpenAPI Explorer dynamically generates the sample code of 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.
SDK for Java
The Java version must be 1.8 or later.
For more information about the source code, see SDK source code for Java or SDK source code for Java in Open Source Software (OSS).
After you add the related dependencies to the pom.xml file, you can use the SDK in Maven projects.
Add the following dependencies to the dependencies field:
<dependency> <groupId>com.aliyun</groupId> <artifactId>green20220302</artifactId> <version>2.2.7</version> </dependency>
Use the SDK for Java.
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(); /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. * Common ways 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 environment variables"); config.setAccessKeySecret("We recommend that you obtain the AccessKey secret of your RAM user from environment variables"); // Change the access region ID and endpoint based on your business requirements. config.setRegionId("ap-southeast-1"); config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com"); // The connection timeout period. Unit: milliseconds. config.setReadTimeout(6000); // The read timeout period. Unit: milliseconds. config.setConnectTimeout(3000); // Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. Client client = new Client(config); JSONObject serviceParameters = new JSONObject(); serviceParameters.put("url", "https://xxxx/xxx/sample.wav"); VoiceModerationRequest voiceModerationRequest = new VoiceModerationRequest(); // Moderation type: multi-language voice moderation (audio_multilingual_global). 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 obtaining voice moderation results
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(); /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. * Common ways 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 environment variables"); config.setAccessKeySecret("We recommend that you obtain the AccessKey secret of your RAM user from environment variables"); // Change the access region ID and endpoint based on your business requirements. config.setRegionId("ap-southeast-1"); config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com"); // The connection timeout period. Unit: milliseconds. config.setReadTimeout(6000); // The read timeout period. Unit: milliseconds. config.setConnectTimeout(3000); // Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. Client client = new Client(config); JSONObject serviceParameters = new JSONObject(); // The task ID that is returned when a voice moderation task is submitted. serviceParameters.put("taskId", "Task ID that is returned when a voice moderation task is submitted"); VoiceModerationResultRequest voiceModerationResultRequest = new VoiceModerationResultRequest(); // Moderation type: multi-language voice moderation (audio_multilingual_global). 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(); } } }
SDK for Python
The Python version must be 3.6 or later.
For more information about the source code, see SDK source code for Python.
Run the following command to install the related dependencies:
pip install alibabacloud_green20220302==2.2.7
Use the SDK for Python.
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( # The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. # We recommend that you do not save the AccessKey ID and the AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of resources within your account may be compromised. # Common ways 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 environment variables', access_key_secret='We recommend that you obtain the AccessKey secret of your RAM user from environment variables', # The connection timeout period. Unit: milliseconds. connect_timeout=10000, # The read timeout period. Unit: milliseconds. read_timeout=3000, region_id='ap-southeast-1', endpoint='green-cip.ap-southeast-1.aliyuncs.com' ) # Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. clt = Client(config) serviceParameters = { 'url': 'https://xxxx/xxx/sample.wav', } voiceModerationRequest = models.VoiceModerationRequest( # Moderation type: multi-language voice moderation (audio_multilingual_global). service='audio_multilingual_global', service_parameters=json.dumps(serviceParameters) ) try: response = clt.voice_moderation(voiceModerationRequest) if response.status_code == 200: # The call is successful. # Obtain the moderation results. 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)
Sample code for obtaining voice moderation results
# 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( # The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. # We recommend that you do not save the AccessKey ID and the AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of resources within your account may be compromised. # Common ways 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 environment variables', access_key_secret='We recommend that you obtain the AccessKey secret of your RAM user from environment variables', # The connection timeout period. Unit: milliseconds. connect_timeout=10000, # The read timeout period. Unit: milliseconds. read_timeout=3000, region_id='ap-southeast-1', endpoint='green-cip.ap-southeast-1.aliyuncs.com' ) # Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. clt = Client(config) # The task ID that is returned when a voice moderation task is submitted. serviceParameters = { "taskId": 'Task ID that is returned when a voice moderation task is submitted' } voiceModerationResultRequest = models.VoiceModerationResultRequest( # Moderation type: multi-language voice moderation (audio_multilingual_global). service='audio_multilingual_global', service_parameters=json.dumps(serviceParameters) ) try: response = clt.voice_moderation_result(voiceModerationResultRequest) if response.status_code == 200: # The call is successful. # Obtain the moderation results. 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)
SDK for PHP
The PHP version must be 5.6 or later.
For more information about the source code, see SDK source code for PHP.
Run the following command to install the related dependencies:
composer require alibabacloud/green-20220302
Use the SDK for PHP.
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([]); /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. * We recommend that you do not save the AccessKey ID and the AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of resources within your account may be compromised. * Common ways 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 environment variables"; $config->accessKeySecret = "We recommend that you obtain the AccessKey secret of your RAM user from environment variables"; // Change the access region ID and endpoint based on your business requirements. $config->regionId = "ap-southeast-1"; $config->endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; // Configure an HTTP proxy. // $config->httpProxy = "http://10.10.xx.xx:xxxx"; // Configure an HTTPS proxy. // $config->httpsProxy = "http://10.10.xx.xx:xxxx"; // Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. $client = new Green($config); $request = new VoiceModerationRequest(); // Moderation type: multi-language voice moderation (audio_multilingual_global). $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 obtaining voice moderation results
<?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([]); /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. * We recommend that you do not save the AccessKey ID and the AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of resources within your account may be compromised. * Common ways 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 environment variables"; $config->accessKeySecret = "We recommend that you obtain the AccessKey secret of your RAM user from environment variables"; // Change the access region ID and endpoint based on your business requirements. $config->regionId = "ap-southeast-1"; $config->endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; // Configure an HTTP proxy. // $config->httpProxy = "http://10.10.xx.xx:xxxx"; // Configure an HTTPS proxy. // $config->httpsProxy = "http://10.10.xx.xx:xxxx"; // Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. $client = new Green($config); $request = new VoiceModerationResultRequest(); // Moderation type: multi-language voice moderation (audio_multilingual_global). $request->service = "audio_multilingual_global"; // The task ID that is returned when a voice moderation task is 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()); }
SDK for Go
SDK for Go
Run the following command to install the related dependencies:
go get github.com/alibabacloud-go/green-20220302
Use the SDK for Go.
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/client" "github.com/alibabacloud-go/tea/tea" "net/http" ) func main() { config := &openapi.Config{ /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. * We recommend that you do not save the AccessKey ID and the AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of resources within your account may be compromised. * Common ways 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 environment variables"), AccessKeySecret: tea.String("We recommend that you obtain the AccessKey secret of your RAM user from environment variables"), // Enter the region ID and endpoint. RegionId: tea.String("ap-southeast-1"), Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"), // Configure an HTTP proxy. //HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"), // Configure an HTTPS proxy. //HttpsProxy: tea.String("https://xx.xx.xx.xx:xxxx"), /** * Set the connection timeout period and the read timeout period. The timeout period for the server to complete a voice moderation request is 10s. * If you set the read timeout to a period shorter than 10s, the server may generate a read timeout error during request processing. */ ConnectTimeout: tea.Int(3000), ReadTimeout: tea.Int(6000), } // Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. client, _err := green.NewClient(config) if _err != nil { panic(_err) } // The URL of the voice to be moderated. serviceParameters, _ := json.Marshal( map[string]interface{}{ "url": "https://xxxx/xxx/sample.wav", }, ) request := green.VoiceModerationRequest{ // 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 obtaining voice moderation results
package main import ( "encoding/json" "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" green "github.com/alibabacloud-go/green-20220302/client" "github.com/alibabacloud-go/tea/tea" "net/http" ) func main() { config := &openapi.Config{ /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. * We recommend that you do not save the AccessKey ID and the AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of resources within your account may be compromised. * Common ways 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 environment variables"), AccessKeySecret: tea.String("We recommend that you obtain the AccessKey secret of your RAM user from environment variables"), // Enter the region ID and endpoint. RegionId: tea.String("ap-southeast-1"), Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"), // Configure an HTTP proxy. // HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"), // Configure an HTTPS proxy. // HttpsProxy: tea.String("https://xx.xx.xx.xx:xxxx"), /** * Set the connection timeout period and the read timeout period. The timeout period for the server to complete a voice moderation request is 10s. * If you set the read timeout to a period shorter than 10s, the server may generate a read timeout error during request processing. */ ConnectTimeout: tea.Int(3000), ReadTimeout: tea.Int(6000), } // Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. client, _err := green.NewClient(config) if _err != nil { panic(_err) } serviceParameters, _ := json.Marshal( map[string]interface{}{ "taskId": "<Task ID>", }, ) request := green.VoiceModerationResultRequest{ // Voice moderation service. 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)) } }
SDK for C#
Run the following command to install the related dependencies:
dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.7
Use the SDK for C#.
Sample code for submitting a voice moderation task
using Newtonsoft.Json; using Tea; namespace AlibabaCloud.SDK.Sample { public class Sample { /** * Use your AccessKey ID and AccessKey secret to initialize your 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) { // If the project code is leaked, the AccessKey pair may be leaked and the security of resources within your account may be compromised. The following sample code is provided for reference only. We recommend that you use a more secure STS method. /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. * We recommend that you do not save the AccessKey ID and the AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of resources within your account may be compromised. * Common ways 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 environment variables", string accessKeySecret = 'We recommend that you obtain the AccessKey secret of your RAM user from environment variables', // Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. 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(); // Voice moderation service. voiceModerationRequest.Service="audio_multilingual_global"; Dictionary<String,Object> task=new Dictionary<string, object>(); // The URL of the voice to be moderated, which is accessible over the Internet. 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 obtaining voice moderation results
using Newtonsoft.Json; using Tea; namespace AlibabaCloud.SDK.Sample { public class Sample { /** * Use your AccessKey ID and AccessKey secret to initialize your 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) { // If the project code is leaked, the AccessKey pair may be leaked and the security of resources within your account may be compromised. The following sample code is provided for reference only. We recommend that you use a more secure STS method. /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. * We recommend that you do not save the AccessKey ID and the AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of resources within your account may be compromised. * Common ways 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 environment variables", string accessKeySecret = 'We recommend that you obtain the AccessKey secret of your RAM user from environment variables', // Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. 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(); // Voice moderation service. voiceModerationResultRequest.Service="audio_multilingual_global"; Dictionary<String,Object> task=new Dictionary<string, object>(); // The ID of the task whose results you want to query. task.Add("taskId","<The ID of the task to be queried>"); 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); } } } }
SDK for Node.js
Run the following command to install the related dependencies:
npm install @alicloud/pop-core
Use the SDK for Node.js.
Sample code for submitting a voice moderation task
const RPCClient = require('@alicloud/pop-core').RPCClient; // Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. var client = new RPCClient({ /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. * We recommend that you do not save the AccessKey ID and the AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of resources within your account may be compromised. * Common ways to obtain environment variables: * Obtain the AccessKey ID of your RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'] * Obtain the AccessKey secret of your RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] */ accessKeyId: 'We recommend that you obtain the AccessKey ID of your RAM user from environment variables', accessKeySecret: 'We recommend that you obtain the AccessKey secret of your RAM user from environment variables', endpoint: 'https://green-cip.ap-southeast-1.aliyuncs.com', apiVersion: '2022-03-02' }); var params = { // Voice moderation service. "Service": "audio_multilingual_global", // The URL of the voice to be moderated. "ServiceParameters":JSON.stringify({ "url": "<The URL of the voice to be moderated>", }) } var requestOption = { method: 'POST', formatParams: false, }; client.request('VoiceModeration', params, requestOption).then((result) => { console.log(JSON.stringify(result)); }, (ex) => { console.log(ex); })
Sample code for obtaining voice moderation results
const RPCClient = require('@alicloud/pop-core').RPCClient; // Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. var client = new RPCClient({ /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. * We recommend that you do not save the AccessKey ID and the AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of resources within your account may be compromised. * Common ways to obtain environment variables: * Obtain the AccessKey ID of your RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'] * Obtain the AccessKey secret of your RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] */ accessKeyId: 'We recommend that you obtain the AccessKey ID of your RAM user from environment variables', accessKeySecret: 'We recommend that you obtain the AccessKey secret of your RAM user from environment variables', endpoint: 'https://green-cip.ap-southeast-1.aliyuncs.com', apiVersion: '2022-03-02' }); var params = { // Voice moderation service. "Service": "audio_multilingual_global", "ServiceParameters":JSON.stringify({ "taskId": "<The ID of the task for which you want to obtain moderation results>", }) } var requestOption = { method: 'POST', formatParams: false, }; client.request('VoiceModerationResult', params, requestOption).then((result) => { console.log(JSON.stringify(result)); }, (ex) => { console.log(ex); })
Calls over HTTPS
Call method
Service request URL: https://green-cip.{region}.aliyuncs.com
Protocol: HTTPS
Method: POST
Common request parameters
The input parameters of the Voice Moderation 2.0 API include common request parameters and operation-specific request parameters. Common request parameters are used by each API operation. The following table describes the common request parameters.
Parameter
Type
Required
Description
Format
String
Yes
The format in which to return the response. Valid values:
JSON (default)
XML
Version
String
Yes
The version number of the Content Moderation 2.0 API. The value is in the YYYY-MM-DD format. Set the value to 2022-03-02.
AccessKeyId
String
Yes
The AccessKey ID that is provided to you by Alibaba Cloud.
Signature
String
Yes
The signature string of the current request. For more information about how signatures are calculated, see the following signature method.
SignatureMethod
String
Yes
The encryption method of the signature string. Set the value to HMAC-SHA1.
Timestamp
String
Yes
The timestamp of a request. Specify the time in the ISO 8601 standard in the yyyy-MM-ddTHH:mm:ssZ format.
The time must be in Coordinated Universal Time (UTC).
For example, 09:13:14 on December 12, 2022 (UTC+8) is written as 2022-12-12T01:13:14Z.
SignatureVersion
String
Yes
The version of the signature encryption algorithm. Set the value to 1.0.
SignatureNonce
String
Yes
A unique and random number that is used to prevent replay attacks. You must use different numbers for different requests.
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 with the services you call.
{ "RequestId":"20B935A9-XXXXXXXX-XXXXXXXX0C2", "Message":"SUCCESS", "Data":{ "TaskId":"au_f_O5xxxxxxxxxxxxxxqa-1****" }, "Code":200 }
Sample code
The following sample responses are formatted to improve readability. Actual responses are not formatted with line breaks or indentation.
Sample code for a moderation task
Sample requests
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 responses
{ "RequestId":"20B935A9-XXXXXXXX-XXXXXXXX0C2", "Message":"SUCCESS", "Data":{ "TaskId":"au_f_O5xxxxxxxxxxxxxxqa-1x****" }, "Code":200 }
Sample code for a result query task
Sample requests
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 responses
{ "RequestId":"926AD581-XXXXXXXXXXXXXX-7902AE", "Message":"success finished", "Data":{ "SliceDetails":[ { "EndTime":6, "StartTime":0, "Text":"It's a nice day.", "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, each request must contain signature information. Voice Moderation 2.0 implements symmetric encryption with an AccessKey pair to authenticate the request sender.
An AccessKey pair is officially issued by Alibaba Cloud. You can apply for and manage it at Alibaba Cloud official website. An AccessKey pair consists of an AccessKey ID and an AccessKey secret. 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 strictly confidential.
To sign a request, perform the following steps:
Create a canonicalized query string by using request parameters.
Sort request parameters in alphabetical order of parameter names. These parameters include the common request parameters and the operation-specific parameters. However, the Signature parameter among common request parameters is not included.
Encode the names and values of the relevant request parameters. Parameter names and values must be URL-encoded by using the UTF-8 character set.
NoteMost libraries that support URL encoding, such as java.net.URLEncoder, comply with the Multipurpose Internet Mail Extensions (MIME) encoding rules of application/x-www-form-urlencoded. If this encoding method is used, replace the plus signs (+) in the encoded strings with %20, the asterisks (*) with %2A, and %7E with a tilde (~). This way, you can obtain an encoded string that is created based on the preceding encoding rules.
Take note of the following encoding rules:
Uppercase letters, lowercase letters, digits, and some special characters such as hyphens (-), underscores (_), periods (.), and tildes (~) do not need to be encoded.
Other characters must be encoded in the
%XY
format, where XY represents the ASCII code of the characters in hexadecimal notation. For example, double quotation marks (") are encoded as%22
.Extended UTF-8 characters must be encoded in the
%XY%ZA...
format.Spaces must be encoded as
%20
. Do not encode spaces as plus signs (+).
Connect the encoded parameter names and values by using equal signs (=).
Sort the equal sign-connected strings by their parameter names in alphabetical order and connect them by using ampersands (&) to obtain the canonicalized query string.
Use the canonicalized query string that is created in Step a.i to create a string to sign based on the following rules:
StringToSign= HTTPMethod + "&" + percentEncode("/") + "&" + percentEncode(CanonicalizedQueryString)
NoteHTTPMethod indicates the HTTP method used to make the request, such as POST. percentEncode("/") encodes forward slashes (/) based on the URL encoding rules described in Step a.ii. The encoded value of a forward slash (/) is
%2F
. percentEncode(CanonicalizedQueryString) specifies the encoded string of the canonicalized query string constructed in Step a.i. The encoded string is obtained by following the URL encoding rules described in Step a.ii.Calculate the hash-based message authentication code (HMAC) value of the string to sign based on the HMAC algorithm that is described in RFC 2104.
NoteUse the Secure Hash Algorithm 1 (SHA1) algorithm to calculate the HMAC value of the string to sign. The AccessKey secret appended by an ampersand (
&
) (ASCII:38) is used as the key for HMAC calculation.Encode the HMAC value in Base64 to obtain the signature string.
Add the signature string to the request as the Signature parameter. This way, the API request is signed.
NoteWhen the signature string is submitted to the Content Moderation service as the final request parameter value, the value must be URL-encoded similar to other parameters based on the rules defined in RFC 3986.