Upload a voice file with API or SDK
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.
-
Voice files must be in WAV or MP3 format and 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
Grant permissions to access cloud resources.
Log on to the Voice Service console with your Alibaba Cloud account (primary account).
Authorize a RAM user. For more information, see Identity management.
Click here to open the quick authorization for Access Control page, and then click Confirm Authorization.
On the authorization page, the role is
AliyunDyvmsCustomAPIRoleand the permission policy isAliyunDyvmsCustomAPIRolePolicy(a system policy).
Obtain a token.
Call the GetToken operation or obtain a token in OpenAPI Explorer.
NoteA token is valid for 30 minutes.
The default value of
TokenTypeisdyvms.
Response:
{ "Message": "OK", "RequestId": "D9CB3933-9FE3-4870-BA8E-2BEE91B69DDD", "Token": "eyJhbGciOiJSUzI1NiIsImtpZCI6ImFjY2Vzc190ZXN0In0.eyJqdGkiOiJUTjhfRzFCaEpETTJ3LWVoeGJZZXRnIiwiaWF0IjoxNjIzMzk0NTI3LCJleHAiOjE2MjMzOTYzMjcsIm5iZiI6MTYyMzM5NDQ2Nywic3ViIjoiWU****", "Code": "OK", "Success": "true" }Determine the file directory.
Use the following code to generate a directory name. The
aliyunUidparameter 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() ; }Upload the voice file.
Postman
API endpoint
The
filenamevalue in this example is for reference only.http://dysmsapi-custom.cn-shanghai.aliyuncs.com/dyvms/upload?filename=asdewqasaaa/TestFile_aaaa3.wavAdd 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
Paramsparameter: For filename, enter the file path/filename (including the file extension) that you obtained in Step 3. For example: asdewqasaaa/TestFile_aaaa3.wavSelect a file.
On the Body tab, select binary, and then select and upload a local file.
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
NoteBefore calling the API, configure environment variables for your access credentials. The environment variables for the AccessKey ID and AccessKey Secret are
VMS_AK_ENVandVMS_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(); } }