阿里云 智能媒体服务 创建并使用高级模板

文档地址 https://help.aliyun.com/zh/ims/user-guide/create-and-use-advanced-templates-1?spm=a2c4g.11186623.help-menu-193643.d_2_4_3_2_0.166a36beZg0Bk9&scm=20140722.H_445389._.OR_help-T_cn~zh-V_1

这组api,可以将AE导出的视频合成模版,通过替换素材合成视频

以下是java代码的调用示例

复制代码
<!--阿里云视频合成-->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>alibabacloud-ice20201109</artifactId>
            <version>6.0.40</version>
        </dependency>

/**
     * 上传文件到OSS
     * @param inputStream
     * @param fileRealName
     * @param fileSize
     * @param path
     * @return
     * @throws IOException
     */
    public Map<String,String> upload(InputStream inputStream,String fileRealName,long fileSize,String path){
        String extension = FileTypeUtils.getFileType(fileRealName);

        //视频文件大小校验
        if (ArrayUtils.contains(MimeTypeUtils.VIDEO_EXTENSION, extension)){
            if (fileSize > Integer.valueOf(videoMaxSize) *  1024 * 1024L){
                throw new ServiceException("视频大小超过限制,请上传小于"+videoMaxSize+"M的文件!");
            }
        }
        //图片大小校验
        if (ArrayUtils.contains(MimeTypeUtils.IMAGE_EXTENSION, extension)){
            if (fileSize > Integer.valueOf(imageMaxSize) *  1024 * 1024L){
                throw new ServiceException("图片大小超过限制,请上传小于"+imageMaxSize+"M的文件!");
            }
        }
        // 避免文件覆盖
        String fileName = UUID.randomUUID().toString() + fileRealName.substring(fileRealName.lastIndexOf("."));

        //上传文件到OSS
        OSS ossClient = new OSSClientBuilder().build(OSSEndPoint,OSSAccessKeyId,OSSAccessKeySecret);
        ossClient.putObject(OSSBucketName,path +"/"+ fileName,inputStream);

        //文件访问路径
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder
                .append(OSSBucketName)
                .append(".")
                .append(OSSEndPoint)
                .append("/")
                .append(path +"/"+ fileName);
        String url = stringBuilder.toString();
//        String url = OSSEndPoint.split("//")[0] + "//" + OSSBucketName + "." + OSSEndPoint.split("//")[0] + "/" + fileName;

        // 关闭ossClient
        ossClient.shutdown();
        /*if(inputStream != null){
            inputStream.close();
        }*/

        Map<String,String> result = new HashMap<>();
        result.put("fileRealName",fileRealName);
        result.put("url",url);
        result.put("fileName",fileName);
        return result;
    }

合成视频

复制代码
package com.ruoyi.image.utils;


import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.DefaultCredentialProvider;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.ice20201109.AsyncClient;
import com.aliyun.sdk.service.ice20201109.models.*;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class AliYunVideoCompositionUtil {
    private final static String accessKeyId = "LTAI5t8ct";
    private final static String accessKeySecret = "WjIH";

    /*private static Client createClient() throws Exception {
        // 方式1:直接从代码中设置(不推荐生产环境使用)
        Config config = new Config();
        config.setAccessKeyId("你的AccessKeyId");
        config.setAccessKeySecret("你的AccessKeySecret");
        // 根据实际情况设置endpoint
        config.setEndpoint("ice.cn-beijing.aliyuncs.com");
        return new Client(config);
    }*/

    /**
     * 添加模版
     * @param templateName
     * @param templateZipFile
     * @return
     */
    public static String addTemplate(String templateName, File templateZipFile) {
        //先将文件上传到OSS
        //Map<String, String> videoTemplate = aliOSSUtils.upload(new FileInputStream(file), file.getName(), file.length(), "videoTemplate");

        // 1. 创建凭证(直接写死)
        Credential credential = Credential.builder().accessKeyId(accessKeyId).accessKeySecret(accessKeySecret).build();
        StaticCredentialProvider provider = StaticCredentialProvider.create(credential);

        AsyncClient build = AsyncClient.builder()
                .region("cn-beijing") // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Endpoint 请参考 https://api.aliyun.com/product/ICE
                                .setEndpointOverride("ice.cn-beijing.aliyuncs.com")
                )
                .build();
        AsyncClient client = build;

        AddTemplateRequest request = AddTemplateRequest.builder()
                .type("VETemplate")
                .name(templateName)
                .config("{\"oss_url\":\"https://java-mmwz-alioss.oss-cn-beijing.aliyuncs.com/videoTemplate/ccc3946e-dc19-497e-8705-ab0b3cfe874e.zip\"}")
                .build();

        CompletableFuture<AddTemplateResponse> addTemplateResponseCompletableFuture = client.addTemplate(request);
        AddTemplateResponse addTemplateResponse = null;
        try {
            addTemplateResponse = addTemplateResponseCompletableFuture.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        System.out.println("templateId : " + addTemplateResponse.getBody().getTemplate().getTemplateId());

        return addTemplateResponse.getBody().getTemplate().getTemplateId();
    }


    /**
     * 获取模版参数
     * @param templateId
     * @return
     */
    public static List<Map<String,String>> getTemplateParams(String templateId) {
        // 1. 创建凭证(直接写死)
        Credential credential = Credential.builder().accessKeyId(accessKeyId).accessKeySecret(accessKeySecret).build();
        StaticCredentialProvider provider = StaticCredentialProvider.create(credential);

        AsyncClient build = AsyncClient.builder()
                .region("cn-beijing") // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Endpoint 请参考 https://api.aliyun.com/product/ICE
                                .setEndpointOverride("ice.cn-beijing.aliyuncs.com")
                )
                .build();
        AsyncClient client = build;
        GetTemplateParamsRequest getTemplateParamsRequest = GetTemplateParamsRequest.builder()
                .templateId(templateId)
                .build();

        CompletableFuture<GetTemplateParamsResponse> response = client.getTemplateParams(getTemplateParamsRequest);
        // Synchronously get the return value of the API request
        GetTemplateParamsResponse resp = null;
        try {
            resp = response.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        List<GetTemplateParamsResponseBody.ParamList> paramList = resp.getBody().getParamList();

        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        for(GetTemplateParamsResponseBody.ParamList param : paramList) {
            Map<String,String> map = new HashMap<String,String>();
            map.put("key", param.getKey());
            map.put("type", param.getType());
            list.add(map);
        }
       return list;
    }

    /**
     * 提交合成视频任务
     * @param templateId
     * @param clipsParam
     * @param outputMediaURL
     * @return
     */
    public static String submitMediaProducingJob(String templateId,Map<String,String> clipsParam,String outputMediaURL) {
        Gson gson = new Gson();
        String json = gson.toJson(clipsParam);


        // 1. 创建凭证(直接写死)
        Credential credential = Credential.builder().accessKeyId(accessKeyId).accessKeySecret(accessKeySecret).build();
        StaticCredentialProvider provider = StaticCredentialProvider.create(credential);

        AsyncClient build = AsyncClient.builder()
                .region("cn-beijing") // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Endpoint 请参考 https://api.aliyun.com/product/ICE
                                .setEndpointOverride("ice.cn-beijing.aliyuncs.com")
                )
                .build();
        AsyncClient client = build;

        SubmitMediaProducingJobRequest submitMediaProducingJobRequest = SubmitMediaProducingJobRequest.builder()
                .templateId(templateId)
                .clipsParam(json)
                .outputMediaConfig("{\"MediaURL\":\""+outputMediaURL+"\"}")
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<SubmitMediaProducingJobResponse> response = client.submitMediaProducingJob(submitMediaProducingJobRequest);
        // Synchronously get the return value of the API request
        SubmitMediaProducingJobResponse resp = null;
        try {
            resp = response.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }

        return resp.getBody().getJobId();
    }

    /**
     * 查询任务结果
     * @param jobId
     * @return
     */
    public static Map<String,String> getMediaProducingJob(String jobId) {
        // 1. 创建凭证(直接写死)
        Credential credential = Credential.builder().accessKeyId(accessKeyId).accessKeySecret(accessKeySecret).build();
        StaticCredentialProvider provider = StaticCredentialProvider.create(credential);

        AsyncClient build = AsyncClient.builder()
                .region("cn-beijing") // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Endpoint 请参考 https://api.aliyun.com/product/ICE
                                .setEndpointOverride("ice.cn-beijing.aliyuncs.com")
                )
                .build();
        AsyncClient client = build;

        GetMediaProducingJobRequest getMediaProducingJobRequest = GetMediaProducingJobRequest.builder()
                .jobId(jobId)
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        CompletableFuture<GetMediaProducingJobResponse> response = client.getMediaProducingJob(getMediaProducingJobRequest);
        // Synchronously get the return value of the API request
        GetMediaProducingJobResponse resp = null;
        try {
            resp = response.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }

        Map<String,String> map = new HashMap<String,String>();
        map.put("status", resp.getBody().getMediaProducingJob().getStatus());// Failed / Init / Success
        map.put("mediaURL", resp.getBody().getMediaProducingJob().getMediaURL());
        return map;
    }

    public static void main(String[] args) {
        /*String s = addTemplate("喜结良缘", null);
        System.out.println(s);*/

        /*List<Map<String, String>> templateParams = getTemplateParams("6a57fc520b9d4818963132eb9c875c49");
        System.out.println(templateParams);*/

        /*Map<String,String> rmap=new HashMap<>();
        rmap.put("Media0","https://java-mmwz-alioss.oss-cn-beijing.aliyuncs.com/0010140a-026d-4a21-ae5e-abad35bf92a3.jpg");
        rmap.put("Media1","https://java-mmwz-alioss.oss-cn-beijing.aliyuncs.com/0010140a-026d-4a21-ae5e-abad35bf92a3.jpg");
        rmap.put("Media2","https://java-mmwz-alioss.oss-cn-beijing.aliyuncs.com/0010140a-026d-4a21-ae5e-abad35bf92a3.jpg");
        rmap.put("Media3","https://java-mmwz-alioss.oss-cn-beijing.aliyuncs.com/0010140a-026d-4a21-ae5e-abad35bf92a3.jpg");
        rmap.put("Media4","https://java-mmwz-alioss.oss-cn-beijing.aliyuncs.com/0010140a-026d-4a21-ae5e-abad35bf92a3.jpg");
        rmap.put("Media5","https://java-mmwz-alioss.oss-cn-beijing.aliyuncs.com/0010140a-026d-4a21-ae5e-abad35bf92a3.jpg");
        rmap.put("Media6","https://java-mmwz-alioss.oss-cn-beijing.aliyuncs.com/0010140a-026d-4a21-ae5e-abad35bf92a3.jpg");
        rmap.put("Media7","https://java-mmwz-alioss.oss-cn-beijing.aliyuncs.com/0010140a-026d-4a21-ae5e-abad35bf92a3.jpg");

        String s = submitMediaProducingJob("6a57fc520b9d4818963132eb9c875c49", rmap, "https://java-mmwz-alioss.oss-cn-beijing.aliyuncs.com/obje777777777777771.mp4");
        System.out.println(s);*/

        Map<String, String> mediaProducingJob = getMediaProducingJob("bc0d3ededc9b44ba99c9611fe0734ac7");
        System.out.println(mediaProducingJob);
    }
}
相关推荐
开开心心就好19 小时前
无需安装的单机塔防游戏轻松畅玩
人工智能·游戏·pdf·音视频·智能家居·语音识别·媒体
开开心心就好19 小时前
这款工具批量卸载软件并清理残留文件
人工智能·游戏·音视频·语音识别·媒体·程序员创富·高考
Hommy881 天前
【开源剪映小助手】媒体处理功能
开源·媒体·剪映小助手
EasyDSS3 天前
私有化视频会议系统/企业级融媒体生产管理平台EasyDSS一体化视频平台赋能各行业数字化
音视频·媒体
BizViewStudio4 天前
甄选 2026:AI 重构新媒体代运营行业的三大核心变革与落地路径
大数据·人工智能·新媒体运营·媒体
lI-_-Il6 天前
赤拳配音 v1.0.3 解锁VIP版:自媒体创作者的AI配音利器
人工智能·媒体
赛博云推-Twitter热门霸屏工具9 天前
Twitter运营完整流程:从0到引流获客全流程拆解(2026)
运维·安全·自动化·媒体·twitter
KIHU快狐9 天前
KIHU快狐|98寸室外触摸屏酷睿I5零售信息展示用
媒体
木斯佳9 天前
HarmonyOS 6实战:AI Action富媒体卡片迭代——实现快照分享
人工智能·harmonyos·媒体