Use o ApsaraVideo Media Processing (MPS) SDK for Java para mesclar e recortar vídeos. A mesclagem combina clipes de diferentes formatos, taxas de bits e resoluções em uma única saída. Esse recurso é comum para adicionar aberturas ou encerramentos, ou para unir segmentos gravados de transmissões ao vivo. Já o recorte extrai um trecho de um vídeo source e o salva como um novo arquivo, ideal para capturar destaques.
Cenários
União de introdução e encerramento: Adicione uma abertura ou um encerramento fixo a um vídeo, ou una segmentos de uma transmissão ao vivo gravada.
Extração de clipes: Recorte um segmento de um vídeo source e exporte-o como um arquivo independente. Esse processo é geralmente usado para capturar destaques.
Efeitos de abertura e encerramento: Insira uma abertura no início do vídeo no modo Picture-in-Picture (PiP) ou anexe um encerramento ao final.
Mesclar vários clipes de vídeo em sequência
O exemplo abaixo recorta o vídeo de entrada a partir de 00:00:03.000, com duração de 00:00:13.000 segundos. Em seguida, mescla o resultado com o segmento de 00:00:01.000 a 00:00:05.030 de um vídeo de abertura. A duração total da saída é de 17,30 segundos.
/**
* Merge multiple video clips in sequence.
* @return
* @throws Exception
*/
public static void mergrUrlListJob() throws Exception {
// Construct output parameters.
JSONArray outputs = new JSONArray();
// Configure the job input. Make sure that the media file used as the job input resides in the same region as the client.
JSONObject input = new JSONObject();
input.put("Bucket", "<your bucket name>");
input.put("Location", "oss-cn-shanghai");
// Configure the job output.
JSONObject output = new JSONObject();
try {
input.put("Object", URLEncoder.encode("mps-test/demo/test.mp4", "utf-8"));
String outPutObject = URLEncoder.encode("mps-test/demo/merge-out.mp4", "utf-8");
output.put("OutputObject", outPutObject);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("input URL encode failed");
}
output.put("TemplateId", "<transcode templateId>");
// Construct data for video clipping.
JSONObject clip = new JSONObject();
// Cut the video from 1.000s to 5.030s.
clip.put("TimeSpan", "{\"Seek\":\"00:00:01.000\",\"Duration\":\"5.30\"}");
// Cut the video from 1.000s to 5.030s that remains from the end of the video.
//clip.put("TimeSpan", "{\"Seek\":\"00:00:01.000\",\"End\":\"5.30\"}");
// Specifies whether to edit the first clip of the video. Valid values: true and false. A value of true specifies that the video clips are merged for a transcoding job after editing. A value of false specifies that the video clips are merged for a transcoding job before editing.
clip.put("ConfigToClipFirstPart", true);
// Construct data for video merging.
JSONArray mergeList = new JSONArray();
JSONObject merge = new JSONObject();
merge.put("MergeURL", "http://bucket-name.oss-cn-shanghai.aliyuncs.com/" + URLEncoder.encode("mps-test/demo/test2mp4", "utf-8"));
merge.put("Start", "00:00:03.000");
merge.put("Duration", "00:00:13.000");
mergeList.add(merge);
output.put("Clip", clip);
output.put("MergeList", mergeList);
outputs.add(output);
com.aliyun.mts20140618.Client client = MergeClipJobs.createClient();
com.aliyun.mts20140618.models.SubmitJobsRequest submitJobsRequest = new com.aliyun.mts20140618.models.SubmitJobsRequest()
// The job input.
.setInput(input.toJSONString())
// The job output configuration.
.setOutputs(outputs.toJSONString())
// The OSS bucket in which the output file is stored.
.setOutputBucket("exampleBucket")
// The region in which the OSS bucket resides.
.setOutputLocation("oss-cn-shanghai")
// The ID of the pipeline.
.setPipelineId("dd3dae411e704030b921e52698e5****");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// Write your own code to display the response of the API operation if necessary.
client.submitJobsWithOptions(submitJobsRequest, runtime);
} catch (TeaException error) {
// Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
// The error message.
System.out.println(error.getMessage());
// The URL for troubleshooting.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
// The error message.
System.out.println(error.getMessage());
// The URL for troubleshooting.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
Mesclar clipes de vídeo usando um arquivo de configuração
Este exemplo recorta o vídeo de entrada a partir de 00:00:03.000, com duração de 00:00:10.000 segundos, e o mescla com o segmento de 00:00:01.000 a 00:00:05.030 da abertura.
O arquivo de configuração mergeConfigfile contém o seguinte:
{"MergeList":[{"MergeURL":"https://bucket-name.oss-cn-beijing.aliyuncs.com/mps-test/demo/test2.mp4","Start":"00:00:03.000","Duration":"00:00:10.000"}]}
/**
* Merge video clips by using the OSS path of a configuration file.
* @return
* @throws Exception
*/
public static void mergrConfigFileJob() throws Exception {
// Construct output parameters.
JSONArray outputs = new JSONArray();
// Configure the job input. Make sure that the media file used as the job input resides in the same region as the client.
JSONObject input = new JSONObject();
input.put("Bucket", "<your bucket name>");
input.put("Location", "oss-cn-shanghai");
// Configure the job output.
JSONObject output = new JSONObject();
try {
input.put("Object", URLEncoder.encode("mps-test/demo/test.mp4", "utf-8"));
String outPutObject = URLEncoder.encode("mps-test/demo/merge-out.mp4", "utf-8");
output.put("OutputObject", outPutObject);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("input URL encode failed");
}
output.put("TemplateId", "<transcode templateId>");
// Construct data for video clipping.
JSONObject clip = new JSONObject();
// Cut the video from 1.000s to 5.030s.
clip.put("TimeSpan", "{\"Seek\":\"00:00:01.000\",\"Duration\":\"5.30\"}");
// Cut the video from 1.000s to 5.030s that remains from the end of the video.
//clip.put("TimeSpan", "{\"Seek\":\"00:00:01.000\",\"End\":\"5.30\"}");
// Specifies whether to edit the first clip of the video. Valid values: true and false. A value of true specifies that the video clips are merged for a transcoding job after editing. A value of false specifies that the video clips are merged for a transcoding job before editing.
clip.put("ConfigToClipFirstPart", true);
output.put("Clip", clip);
// The OSS path of the configuration file must be an HTTP URL.
output.put("MergeConfigUrl", "http://bucket-name.oss-cn-shanghai.aliyuncs.com/mps-test/demo/mergeConfigfile");
outputs.add(output);
com.aliyun.mts20140618.Client client = MergeClipJobs.createClient();
com.aliyun.mts20140618.models.SubmitJobsRequest submitJobsRequest = new com.aliyun.mts20140618.models.SubmitJobsRequest()
// The job input.
.setInput(input.toJSONString())
// The job output configuration.
.setOutputs(outputs.toJSONString())
// The OSS bucket in which the output file is stored.
.setOutputBucket("exampleBucket")
// The region in which the OSS bucket resides.
.setOutputLocation("oss-cn-shanghai")
// The ID of the pipeline.
.setPipelineId("dd3dae411e704030b921e52698e5****");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// Write your own code to display the response of the API operation if necessary.
client.submitJobsWithOptions(submitJobsRequest, runtime);
} catch (TeaException error) {
// Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
// The error message.
System.out.println(error.getMessage());
// The URL for troubleshooting.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
// The error message.
System.out.println(error.getMessage());
// The URL for troubleshooting.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
Inserir uma abertura ou anexar um encerramento a um vídeo
No exemplo a seguir, o sistema insere uma abertura (680 x 480) a partir do terceiro segundo do vídeo de entrada no modo Picture-in-Picture (PiP) e anexa um encerramento (680 x 480) ao final. Um fundo branco preenche a área vazia após o encerramento.
Os objetos do OSS referenciados nas URLs de abertura e encerramento devem ter codificação UTF-8, e as URLs devem usar HTTP. Para mais informações, consulte Codificação de URL.
/**
* Embed opening parts at the beginning of the input video or add ending parts to the end of the input video.
* @return
* @throws Exception
*/
public static void openAndTailJob() throws Exception {
// Construct output parameters.
JSONArray outputs = new JSONArray();
// Configure the job input. Make sure that the media file used as the job input resides in the same region as the client.
JSONObject input = new JSONObject();
input.put("Bucket", "<your bucket name>");
input.put("Location", "oss-cn-shanghai");
// Configure the job output.
JSONObject output = new JSONObject();
try {
input.put("Object", URLEncoder.encode("mps-test/demo/test.mp4", "utf-8"));
String outPutObject = URLEncoder.encode("mps-test/demo/merge-out.mp4", "utf-8");
output.put("OutputObject", outPutObject);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("input URL encode failed");
}
output.put("TemplateId", "<transcode templateId>");
JSONArray openingList = new JSONArray();
JSONObject opening = new JSONObject();
opening.put("OpenUrl", "http://bucket-name.oss-cn-shanghai.aliyuncs.com/" + URLEncoder.encode("mps-test/demo/open.mp4", "utf-8"));
opening.put("Start", "3");
opening.put("Width", "680");
opening.put("Height", "480");
openingList.add(opening);
JSONArray tailSlateList = new JSONArray();
JSONObject tailSlate = new JSONObject();
// Objects specified by URLs of the opening and ending parts must be UTF-8-encoded.
tailSlate.put("TailUrl", "http://bucket-name.oss-cn-shanghai.aliyuncs.com/" + URLEncoder.encode("mps-test/demo/tail.mp4", "utf-8"));
tailSlate.put("BlendDuration", "2");
tailSlate.put("Width", "680");
tailSlate.put("Height", "480");
tailSlate.put("IsMergeAudio", true);
tailSlate.put("BgColor", "White");
tailSlateList.add(tailSlate);
output.put("OpeningList", openingList);
output.put("TailSlateList", tailSlateList);
outputs.add(output);
com.aliyun.mts20140618.Client client = MergeClipJobs.createClient();
com.aliyun.mts20140618.models.SubmitJobsRequest submitJobsRequest = new com.aliyun.mts20140618.models.SubmitJobsRequest()
// The job input.
.setInput(input.toJSONString())
// The job output configuration.
.setOutputs(outputs.toJSONString())
// The OSS bucket in which the output file is stored.
.setOutputBucket("exampleBucket")
// The region in which the OSS bucket resides.
.setOutputLocation("oss-cn-shanghai")
// The ID of the pipeline.
.setPipelineId("dd3dae411e704030b921e52698e5****");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// Write your own code to display the response of the API operation if necessary.
client.submitJobsWithOptions(submitJobsRequest, runtime);
} catch (TeaException error) {
// Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
// The error message.
System.out.println(error.getMessage());
// The URL for troubleshooting.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
// The error message.
System.out.println(error.getMessage());
// The URL for troubleshooting.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
Código de exemplo completo
Os três exemplos usam submitJobsWithOptions para enviar jobs de transcodificação assíncronos. O cliente usa credenciais de variáveis de ambiente para inicialização.
package com.alibaba.bltest.api_v2;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.tea.TeaException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class MergeClipJobs {
/**
* <b>description</b> :
* <p>Use your AccessKey pair to initialize the client.</p>
* @return Client
*
* @throws Exception
*/
public static com.aliyun.mts20140618.Client createClient() throws Exception {
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.endpoint = "mts.cn-shanghai.aliyuncs.com";
return new com.aliyun.mts20140618.Client(config);
}
/**
* Merge multiple video clips in sequence.
* @return
* @throws Exception
*/
public static void mergrUrlListJob() throws Exception {
// Construct output parameters.
JSONArray outputs = new JSONArray();
// Configure the job input. Make sure that the media file used as the job input resides in the same region as the client.
JSONObject input = new JSONObject();
input.put("Bucket", "<your bucket name>");
input.put("Location", "oss-cn-shanghai");
// Configure the job output.
JSONObject output = new JSONObject();
try {
input.put("Object", URLEncoder.encode("mps-test/demo/test.mp4", "utf-8"));
String outPutObject = URLEncoder.encode("mps-test/demo/merge-out.mp4", "utf-8");
output.put("OutputObject", outPutObject);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("input URL encode failed");
}
output.put("TemplateId", "<transcode templateId>");
// Construct data for video clipping.
JSONObject clip = new JSONObject();
// Cut the video from 1.000s to 5.030s.
clip.put("TimeSpan", "{\"Seek\":\"00:00:01.000\",\"Duration\":\"5.30\"}");
// Cut the video from 1.000s to 5.030s that remains from the end of the video.
//clip.put("TimeSpan", "{\"Seek\":\"00:00:01.000\",\"End\":\"5.30\"}");
// Specifies whether to edit the first clip of the video. Valid values: true and false. A value of true specifies that the video clips are merged for a transcoding job after editing. A value of false specifies that the video clips are merged for a transcoding job before editing.
clip.put("ConfigToClipFirstPart", true);
// Construct data for video merging.
JSONArray mergeList = new JSONArray();
JSONObject merge = new JSONObject();
merge.put("MergeURL", "http://bucket-name.oss-cn-shanghai.aliyuncs.com/" + URLEncoder.encode("mps-test/demo/test2mp4", "utf-8"));
merge.put("Start", "00:00:03.000");
merge.put("Duration", "00:00:13.000");
mergeList.add(merge);
output.put("Clip", clip);
output.put("MergeList", mergeList);
outputs.add(output);
com.aliyun.mts20140618.Client client = MergeClipJobs.createClient();
com.aliyun.mts20140618.models.SubmitJobsRequest submitJobsRequest = new com.aliyun.mts20140618.models.SubmitJobsRequest()
// The job input.
.setInput(input.toJSONString())
// The job output configuration.
.setOutputs(outputs.toJSONString())
// The OSS bucket in which the output file is stored.
.setOutputBucket("exampleBucket")
// The region in which the OSS bucket resides.
.setOutputLocation("oss-cn-shanghai")
// The ID of the pipeline.
.setPipelineId("dd3dae411e704030b921e52698e5****");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// Write your own code to display the response of the API operation if necessary.
client.submitJobsWithOptions(submitJobsRequest, runtime);
} catch (TeaException error) {
// Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
// The error message.
System.out.println(error.getMessage());
// The URL for troubleshooting.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
// The error message.
System.out.println(error.getMessage());
// The URL for troubleshooting.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
/**
* Merge video clips by using the OSS path of a configuration file.
* @return
* @throws Exception
*/
public static void mergrConfigFileJob() throws Exception {
// Construct output parameters.
JSONArray outputs = new JSONArray();
// Configure the job input. Make sure that the media file used as the job input resides in the same region as the client.
JSONObject input = new JSONObject();
input.put("Bucket", "<your bucket name>");
input.put("Location", "oss-cn-shanghai");
// Configure the job output.
JSONObject output = new JSONObject();
try {
input.put("Object", URLEncoder.encode("mps-test/demo/test.mp4", "utf-8"));
String outPutObject = URLEncoder.encode("mps-test/demo/merge-out.mp4", "utf-8");
output.put("OutputObject", outPutObject);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("input URL encode failed");
}
output.put("TemplateId", "<transcode templateId>");
// Construct data for video clipping.
JSONObject clip = new JSONObject();
// Cut the video from 1.000s to 5.030s.
clip.put("TimeSpan", "{\"Seek\":\"00:00:01.000\",\"Duration\":\"5.30\"}");
// Cut the video from 1.000s to 5.030s that remains from the end of the video.
//clip.put("TimeSpan", "{\"Seek\":\"00:00:01.000\",\"End\":\"5.30\"}");
// Specifies whether to edit the first clip of the video. Valid values: true and false. A value of true specifies that the video clips are merged for a transcoding job after editing. A value of false specifies that the video clips are merged for a transcoding job before editing.
clip.put("ConfigToClipFirstPart", true);
output.put("Clip", clip);
// The OSS path of the configuration file must be an HTTP URL.
output.put("MergeConfigUrl", "http://bucket-name.oss-cn-shanghai.aliyuncs.com/mps-test/demo/mergeConfigfile");
outputs.add(output);
com.aliyun.mts20140618.Client client = MergeClipJobs.createClient();
com.aliyun.mts20140618.models.SubmitJobsRequest submitJobsRequest = new com.aliyun.mts20140618.models.SubmitJobsRequest()
// The job input.
.setInput(input.toJSONString())
// The job output configuration.
.setOutputs(outputs.toJSONString())
// The OSS bucket in which the output file is stored.
.setOutputBucket("exampleBucket")
// The region in which the OSS bucket resides.
.setOutputLocation("oss-cn-shanghai")
// The ID of the pipeline.
.setPipelineId("dd3dae411e704030b921e52698e5****");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// Write your own code to display the response of the API operation if necessary.
client.submitJobsWithOptions(submitJobsRequest, runtime);
} catch (TeaException error) {
// Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
// The error message.
System.out.println(error.getMessage());
// The URL for troubleshooting.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
// The error message.
System.out.println(error.getMessage());
// The URL for troubleshooting.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
/**
* Embed opening parts at the beginning of the input video or add ending parts to the end of the input video.
* @return
* @throws Exception
*/
public static void openAndTailJob() throws Exception {
// Construct output parameters.
JSONArray outputs = new JSONArray();
// Configure the job input. Make sure that the media file used as the job input resides in the same region as the client.
JSONObject input = new JSONObject();
input.put("Bucket", "<your bucket name>");
input.put("Location", "oss-cn-shanghai");
// Configure the job output.
JSONObject output = new JSONObject();
try {
input.put("Object", URLEncoder.encode("mps-test/demo/test.mp4", "utf-8"));
String outPutObject = URLEncoder.encode("mps-test/demo/merge-out.mp4", "utf-8");
output.put("OutputObject", outPutObject);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("input URL encode failed");
}
output.put("TemplateId", "<transcode templateId>");
JSONArray openingList = new JSONArray();
JSONObject opening = new JSONObject();
opening.put("OpenUrl", "http://bucket-name.oss-cn-shanghai.aliyuncs.com/" + URLEncoder.encode("mps-test/demo/open.mp4", "utf-8"));
opening.put("Start", "3");
opening.put("Width", "680");
opening.put("Height", "480");
openingList.add(opening);
JSONArray tailSlateList = new JSONArray();
JSONObject tailSlate = new JSONObject();
// Objects specified by URLs of the opening and ending parts must be UTF-8-encoded.
tailSlate.put("TailUrl", "http://bucket-name.oss-cn-shanghai.aliyuncs.com/" + URLEncoder.encode("mps-test/demo/tail.mp4", "utf-8"));
tailSlate.put("BlendDuration", "2");
tailSlate.put("Width", "680");
tailSlate.put("Height", "480");
tailSlate.put("IsMergeAudio", true);
tailSlate.put("BgColor", "White");
tailSlateList.add(tailSlate);
output.put("OpeningList", openingList);
output.put("TailSlateList", tailSlateList);
outputs.add(output);
com.aliyun.mts20140618.Client client = MergeClipJobs.createClient();
com.aliyun.mts20140618.models.SubmitJobsRequest submitJobsRequest = new com.aliyun.mts20140618.models.SubmitJobsRequest()
// The job input.
.setInput(input.toJSONString())
// The job output configuration.
.setOutputs(outputs.toJSONString())
// The OSS bucket in which the output file is stored.
.setOutputBucket("exampleBucket")
// The region in which the OSS bucket resides.
.setOutputLocation("oss-cn-shanghai")
// The ID of the pipeline.
.setPipelineId("dd3dae411e704030b921e52698e5****");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// Write your own code to display the response of the API operation if necessary.
client.submitJobsWithOptions(submitJobsRequest, runtime);
} catch (TeaException error) {
// Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
// The error message.
System.out.println(error.getMessage());
// The URL for troubleshooting.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
// The error message.
System.out.println(error.getMessage());
// The URL for troubleshooting.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
}