阿里云媒体处理

一、介绍:

媒体处理(ApsaraVideo for Media Processing,原MTS)是一种多媒体数据处理服务。它以经济、弹性和高可扩展的音视频转换方法,将多媒体数据转码成适合在全平台播放的格式。并基于海量数据深度学习,对音视频的内容、文字、语音、场景多模态分析,实现智能审核、内容理解、智能编辑。

相关API连接:https://help.aliyun.com/product/29194.html?spm=a2c4g.11186623.6.168.YjvZGq

二、使用

这里主要使用阿里云的视频转码。转码可以使用自定义模板或者阿里云默认模板,本人使用阿里云默认模板

视频转码步骤:1.提交视频转码任务 2.获取视频转码任务结果。

在我们提交视频转码任务时并没有返回视频转码结果,返回的是任务id。而阿里云提供两种获取视频:

1.根据任务id轮询转码查询接口 

2.异步回调开启消息通知(需要购买消息通知服务,当完成转码将会向客户发送一条消息)

准备工作:

管道id:登陆控制台,查看管道id

顶置模板id:在这里可以查看需要用的模板id


提交的转码任务:

/**
 * Author: hezishan
 * Date: 2018/5/2.
 * Description:
 **/
@Service
public class SubmitJobServiece {

    private static final Logger LOGGER = Logger.getLogger(SubmitJobServiece.class);

    /**
     * 配置信息
     */
    @Autowired
    private OSSConfiguration configuration;

    /**
     * 获取iacsClient
     */
    private IAcsClient acsClient = IAcsClientFactory.getInstance();

    /**
     * 初始化input参数
     *
     * @param location
     * @param bucketName
     * @param ossInputObject 转码文件
     * @return
     */
    private JSONObject initInputParams(String location, String bucketName, String ossInputObject) {
        JSONObject inputObj = new JSONObject();
        try {
            inputObj.put("Location", location);
            inputObj.put("Bucket", bucketName);
            inputObj.put("Object", URLEncoder.encode(ossInputObject, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            throw new ServiceException("input URL encode failed");
        }
        return inputObj;
    }

    /**
     * 初始化output
     *
     * @param outputOSSObject
     * @param templateId
     * @return
     */
    private JSONObject initOutputParams(String outputOSSObject, String templateId) {
        JSONObject outputObj = new JSONObject();
        try {
            outputObj.put("OutputObject", URLEncoder.encode(outputOSSObject, "utf-8"));
            outputObj.put("TemplateId", templateId);
        } catch (UnsupportedEncodingException e) {
            throw new ServiceException("input URL encode failed");
        }
        return outputObj;
    }


    /**
     * 提交转码任务
     *
     * @param ossInputObject
     * @param outputOSSObject
     * @param templateId
     * @return
     */
    public Map<String, String> submitTransferJob(String ossInputObject, String outputOSSObject, String templateId) {
        Map<String, String> map = new HashMap<String, String>();
        // 创建API请求并设置参数
        SubmitJobsRequest request = new SubmitJobsRequest();
        JSONArray outputs = new JSONArray();
        outputs.add(initOutputParams(outputOSSObject, templateId));
        request.setOutputs(outputs.toJSONString());
        request.setInput(initInputParams(configuration.getOssLocation(), configuration.getBucketName(), ossInputObject).toJSONString());
        request.setOutputBucket(configuration.getBucketName());
        request.setOutputLocation(configuration.getOssLocation());
        request.setPipelineId(configuration.getPipelineId());
        SubmitJobsResponse response;
        try {
            response = acsClient.getAcsResponse(request);
            if (response.getJobResultList().get(0).getSuccess()) {
                String jobId = response.getJobResultList().get(0).getJob().getJobId();
                map.put("jobId", jobId);
                map.put("code", "1");
            } else {
                map.put("code", "0");
                LOGGER.info("[SubmitJobServiece.class:submitTransferJob]:" + "SubmitJobs Failed code:" + response.getJobResultList().get(0).getCode() +
                        " message:" + response.getJobResultList().get(0).getMessage());
            }

        } catch (Exception e) {
            map.put("code", "0");
            throw new ServiceException(e.getMessage());
        }
        return map;
    }
}

调用工具类

    /**
     * 提交单个转码任务
     *
     * @param ossInputObject
     * @param type
     * @return
     */
    public Map<String, String> submitJob(String ossInputObject, Integer type) {
        String tempId = "";
        if (Mp4Type.STANDARD_MP4 == type) {
            tempId = configuration.getTemIdOfStandardMp4();
        } else if (Mp4Type.HIGH_MP4 == type) {
            tempId = configuration.getTemIdOfHighMp4();
        } else {
            tempId = configuration.getTemIdOfFullMp4();
        }
        String outputObject = OSSUtils.generateTransferKey(configuration.getSuffxx());
        return submitJobServiece.submitTransferJob(ossInputObject, outputObject, tempId);
    

本人在提交转码任务时将任务id保存在表中,开启定时器扫描表的数据,轮询查询转码任务完成情况:

**
 * Author: hezishan
 * Date: 2018/5/3.
 * Description: 查询转码轮询定时任务
 **/
public class QueryJob implements Job {

    private static final Logger LOGGER = Logger.getLogger(QueryJob.class);

    private OSSConfiguration configuration;

    private JobInfoDao jobInfoDao;

    private RecordDao recordDao;

    /**
     * 获取iacsClient
     */
    private IAcsClient acsClient = IAcsClientFactory.getInstance();

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //通过bean获取对象
        configuration = (OSSConfiguration) SpringUtils.getBean("OSSConfiguration");
        recordDao = (RecordDao) SpringUtils.getBean("recordDao");
        jobInfoDao = (JobInfoDao) SpringUtils.getBean("jobInfoDao");

        List<JobInfo> jobInfos = jobInfoDao.findByIsQuery(0);
        LOGGER.info("[QueryJob.class:execute]:查询转码任务数量:" + jobInfos.size());
        List<Map<String, String>> resultlist = new ArrayList<Map<String, String>>();
        try {
            if (jobInfos != null && jobInfos.size() > 0) {
                for (JobInfo info : jobInfos) {
                    QueryJobListRequest request = new QueryJobListRequest();
                    request.setJobIds(info.getJobList());
                    QueryJobListResponse response = acsClient.getAcsResponse(request);
                    int count = 0;
                    if (response.getJobList() != null && response.getJobList().size() > 0) {
                        for (int i = 0; i < response.getJobList().size(); i++) {
                            Map<String, String> map = new HashMap<String, String>();
                            QueryJobListResponse.Job job = response.getJobList().get(i);
                            String state = job.getState();
                            if (JobType.SUCESS.equals(state)) {
                                map.put("type", handleType(job.getOutput().getTemplateId()));
                                map.put("inputObject", job.getInput().getObject());
                                map.put("outputObject", job.getOutput().getOutputFile().getObject());
                                resultlist.add(map);
                                count++;
                            } else if (JobType.FAIL.equals(state)) {
                                LOGGER.info("[QueryJob.class:execute]:任务id:" + job.getJobId() + "转码任务失败");
                                count = -3;
                            }
                        }
                    }
                    if (count == 3) {
                        //成功,更新数据库
                        info.setIsQuery(1);
                        info.setUpdateTime(new Date());
                        jobInfoDao.save(info);
                        String standardUrl = "";
                        String highUrl = "";
                        String fullUrl = "";
                        for (Map<String, String> map : resultlist) {
                            String type = map.get("type");
                            if ("standard".equals(type)) {
                                standardUrl = OSSUtils.generateResponseUrl(configuration.getBucketName(), configuration.getEndPoint(), map.get("outputObject"));
                            }
                            if ("high".equals(type)) {
                                highUrl = OSSUtils.generateResponseUrl(configuration.getBucketName(), configuration.getEndPoint(), map.get("outputObject"));
                            }
                            if ("full".equals(type)) {
                                fullUrl = OSSUtils.generateResponseUrl(configuration.getBucketName(), configuration.getEndPoint(), map.get("outputObject"));
                            }
                        }
                        saveRecord(resultlist.get(0).get("inputObject"), standardUrl, highUrl, fullUrl);
                        LOGGER.info("[QueryJob.class:execute]:任务id:" + info.getJobList() + "转码任务成功");
                        return;
                    }
                    if (count == 0) {
                        LOGGER.info("[QueryJob.class:execute]:任务id:" + info.getJobList() + "转码任务未完成");
                        return;
                    }
                    if (count < 0) {
                        info.setIsQuery(2);
                        info.setUpdateTime(new Date());
                        jobInfoDao.save(info);
                        String yunUrl = OSSUtils.generateResponseUrl(configuration.getBucketName(), configuration.getEndPoint(), resultlist.get(0).get("inputObject"));
                        saveRecord(resultlist.get(0).get("inputObject"), yunUrl, yunUrl, yunUrl);
                        LOGGER.info("[QueryJob.class:execute]:任务id:" + info.getJobList() + "转码任务失败");
                        return;
                    }

                }
            }

        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }


    /**
     * 保存record
     *
     * @param yunUrl
     * @param standardUrl
     * @param highUrl
     * @param fullUrl
     */
    private void saveRecord(String yunUrl, String standardUrl, String highUrl, String fullUrl) {
        String[] url = yunUrl.split("%2F");
        yunUrl = url[url.length - 1];
        Record record = recordDao.findByYunUrlEndingWith(yunUrl);
        if (record != null) {
            record.setStandUrl(standardUrl);
            record.setHighUrl(highUrl);
            record.setFullUrl(fullUrl);
            recordDao.save(record);
        }
    }


    /**
     * 处理类型
     *
     * @param tempId
     * @return
     */
    private String handleType(String tempId) {
        String result = "";
        if (configuration.getTemIdOfStandardMp4().equals(tempId)) {
            result = "standard";
            return result;
        }
        if (configuration.getTemIdOfHighMp4().equals(tempId)) {
            result = "high";
            return result;
        }
        if (configuration.getTemIdOfFullMp4().equals(tempId)) {
            result = "full";
            return result;
        }
        return result;
    }
}


猜你喜欢

转载自blog.csdn.net/hzs33/article/details/80207444