Upload a voice file with API or SDK

更新时间:
复制 MD 格式

You can upload a voice file by calling an API or using an SDK. This method supports outbound calls only in dedicated mode. After you upload a voice file, it enters a review process that typically completes within two hours.

Note
  • Select a WAV or MP3 file that is smaller than 2 MB.

  • URL: http://dysmsapi-custom.cn-shanghai.aliyuncs.com/dyvms/upload?filename=test.wav.

  • We recommend using the voice file upload feature in the Voice Service console. For more information, see Upload a voice file by using the console.

Request parameters

Parameter

Description

Example

Position

Remarks

filename

The name of the voice file.

test.wav

path

The name of the file, including the extension. This parameter is required.

authorization

The authorization parameter.

ZmY4MDgwODEzYzM****

header

The token obtained by calling the GetToken operation.

Request example

POST http://dysmsapi-custom.cn-shanghai.aliyuncs.com/dyvms/upload?filename=test.wavHTTP/1.1
 Host:192.168.0.1:8883
 content-length: 1390
 Accept:application/json;
 Content-Type:application/octet-stream;charset=utf-8;
authorization:ZmY4MDgwODEzYzM3ZGE1MzAxM2M4MDRmODA3MjAwN2M6MjAxMzAyMDExN****zA=

Response example

{
 "code": "OK",
 "msg": "success",
 "data": {
 "voiceCode": "The ID of the voice file. You can use this ID for voice notifications."
 }
}

Procedure

  1. Grant permissions to access cloud resources.

    1. Log on to the Voice Service console with your Alibaba Cloud account (primary account).

    2. Authorize a RAM user. For more information, see Authorize a RAM user.

    3. Click here to open the quick authorization for Access Control page, and then click Confirm Authorization.

      On the authorization page, the role is AliyunDyvmsCustomAPIRole and the permission policy is AliyunDyvmsCustomAPIRolePolicy (a system policy).

  2. Obtain a token.

    Call the GetToken operation or obtain a token in OpenAPI Explorer.

    Note
    • A token is valid for 30 minutes.

    • The default value of TokenType is dyvms.

    Response:

    {
        "Message": "OK",
        "RequestId": "D9CB3933-9FE3-4870-BA8E-2BEE91B69DDD",
        "Token": "eyJhbGciOiJSUzI1NiIsImtpZCI6ImFjY2Vzc190ZXN0In0.eyJqdGkiOiJUTjhfRzFCaEpETTJ3LWVoeGJZZXRnIiwiaWF0IjoxNjIzMzk0NTI3LCJleHAiOjE2MjMzOTYzMjcsIm5iZiI6MTYyMzM5NDQ2Nywic3ViIjoiWU****",
        "Code": "OK",
        "Success": "true"
    }
  3. Determine the file directory.

    Use the following code to generate a directory name. The aliyunUid parameter specifies the UID of your primary account.

     private String convertASCII(String aliyunUid){
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < aliyunUid.length(); i++) {
                stringBuilder.append((char)(aliyunUid.charAt(i)+ 51 ));
            }
            return stringBuilder.toString() ;
     }
  4. Upload the voice file.

    Postman

    1. API endpoint

      The filename value in this example is for reference only.

      http://dysmsapi-custom.cn-shanghai.aliyuncs.com/dyvms/upload?filename=asdewqasaaa/TestFile_aaaa3.wav
    2. Add parameters.

      Add a header parameter: for authorization, enter the token that you obtained in Step 2. For example: eyJhbGciOiJSUzI1NiIsImtpZCI6ImFjY2Vzc190ZXN0In0.eyJqdGkiOiJUTjhfRzFCaEpETTJ3LWVoeGJZZXRnIiwiaWF0IjoxNjIzMzk0NTI3LCJleHAiOjE2MjMzOTYzMjcsIm5iZiI6MTYyMzM5NDQ2Nywic3ViIjoiWU****

      Add the Accept parameter and set its value to application/json.

      Add the Params parameter: For filename, enter the file path/filename (including the file extension) that you obtained in Step 3. For example: asdewqasaaa/TestFile_aaaa3.wav

    3. Select a file.

      On the Body tab, select binary, and then select and upload a local file.

    4. Response

      {
          "code": "OK",
          "data": {
              "voiceCode": "xxx-0b31-491a-be65-98b53db4b8ac.wav"
          },
          "msg": "success"
      }

    API

    Call the HTTP service endpoint http://dysmsapi-custom.cn-shanghai.aliyuncs.com/dyvms/upload to upload a voice file.

    Code example

    Note

    Before calling the API, configure environment variables for your access credentials. The environment variables for the AccessKey ID and AccessKey Secret are VMS_AK_ENV and VMS_SK_ENV. For more information, see Configure environment variables on Linux, macOS, and Windows.

    Token dependencies

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>dysmsapi20170525</artifactId>
      <version>2.1.4</version>
    </dependency>

    JAR package for HTTP upload

    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.13</version>
     </dependency>
    package com.aliyun.sample;
    import com.aliyun.dysmsapi20170525.models.GetTokenResponse;
    import com.aliyun.tea.TeaException;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.net.URLEncoder;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.InputStreamEntity;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.util.EntityUtils;
    public class Sample {
      /**
       * Use the AccessKey ID and AccessKey Secret to initialize the client.
       *
       * @param accessKey Id
       * @param accessKey Secret
       * @return Client
       * @throws Exception
       */
      public static com.aliyun.dysmsapi20170525.Client createClient(
        String accessKeyId,
        String accessKeySecret
      ) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
          // TODO: Replace this with your AccessKey ID.
          .setAccessKeyId(accessKeyId)
          // TODO: Replace this with your AccessKey Secret.
          .setAccessKeySecret(accessKeySecret);
        // The endpoint of the service.
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
      }
      public static void main(String[] args_) throws Exception {
        String token = null;
        java.util.List<String> args = java.util.Arrays.asList(args_);
        // Your Alibaba Cloud AccessKey ID has full permissions for all APIs, which poses a high security risk. We strongly recommend that you create and use a RAM user for API calls and daily operations. To create a RAM user, log on to the RAM console.
        // This example shows how to store the AccessKey ID and AccessKey Secret in environment variables. You can also store them in a configuration file based on your business needs.
        // We strongly recommend that you do not hard-code the AccessKey ID and AccessKey Secret in your code. This can lead to credential leaks.
        com.aliyun.dyvmsapi20170525.Client client = Sample.createClient(
          System.getenv("VMS_AK_ENV"),
          System.getenv("VMS_SK_ENV")
        );
        com.aliyun.dysmsapi20170525.models.GetTokenRequest getTokenRequest = new com.aliyun.dysmsapi20170525.models.GetTokenRequest()
          .setTokenType("dyvms"); // The `tokenType` for Voice Service is fixed to `dyvms`.
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        // Obtain a token, or reuse the one from Step 2.
        try {
          // You must add your own logic to print the API response.
          GetTokenResponse response = client.getTokenWithOptions(
            getTokenRequest,
            runtime
          );
          if (response != null && "OK".equals(response.getBody().getCode())) {
            token = response.getBody().getToken();
          }
        } catch (TeaException error) {
          // If needed, print the error.
          com.aliyun.teautil.Common.assertAsString(error.message);
          throw error;
        } catch (Exception _error) {
          TeaException error = new TeaException(_error.getMessage(), _error);
          // If needed, print the error.
          com.aliyun.teautil.Common.assertAsString(error.message);
          throw _error;
        }
        String dir = convertASCII("aliyunUid"); // TODO: Replace this with the UID of your primary account.
        String fileName = dir + "/" + "TestFile_aaaa17.wav"; // TODO: Specify the destination file name and extension.
        fileName = URLEncoder.encode(fileName, "UTF-8");
        @SuppressWarnings("deprecation")
        HttpClient ht = new DefaultHttpClient();
        HttpPost post = new HttpPost(
          "http://dysmsapi-custom.cn-shanghai.aliyuncs.com/dyvms/upload?filename=" +
          fileName
        );
        HttpResponse rs = null;
        try {
          File file = new File("C:\\Users\\...\\TestFile.wav"); // TODO: Specify the path to your local file.
          //System.out.println(file.exists());
          // Package the file stream into an InputStreamEntity.
          post.setEntity(
            new InputStreamEntity(new FileInputStream(file), file.length())
          );
          // Set the request content type. If you do not explicitly set this header, the default value is text/plain. Different content types may cause parsing failures on the server.
          post.addHeader("Content-Type", "application/octet-stream");
          post.addHeader("authorization", token);
          // Send the request.
          rs = ht.execute(post);
          System.out.println(
            "" +
            rs.getStatusLine().getStatusCode() +
            " " +
            EntityUtils.toString(rs.getEntity(), "utf-8")
          );
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          // Release the resources.
          if (rs != null) {
            try {
              EntityUtils.consume(rs.getEntity());
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        }
      }
      private static String convertASCII(String aliyunUid) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < aliyunUid.length(); i++) {
          stringBuilder.append((char) (aliyunUid.charAt(i) + 51));
        }
        return stringBuilder.toString();
      }
    }