Tous les produits
Search
Centre de documentation

ApsaraVideo VOD:Media processing

Dernière mise à jour :Aug 10, 2026

Exemples d'utilisation du SDK Java pour soumettre des tâches de transcodage et de capture d'images, interroger les données de capture et prétraiter les vidéos dans le studio de production.

Prérequis

Avant de commencer, assurez-vous de disposer des éléments suivants :

  • Un compte Alibaba Cloud avec ApsaraVideo VOD activé

  • Une paire AccessKey (AccessKey ID et AccessKey secret) configurée en tant que variables d'environnement

  • Un utilisateur Resource Access Management (RAM) disposant des autorisations ApsaraVideo VOD requises

  • Le SDK ApsaraVideo VOD pour Java ajouté aux dépendances de votre projet

Pour les opérations d'API non couvertes ici, consultez OpenAPI Explorer. Sélectionnez une opération d'API, configurez les paramètres dans l'onglet Parameters puis cliquez sur Initiate Call. Téléchargez le code généré depuis l'onglet SDK Sample Code.

Initialiser un client

Avant d'appeler toute opération d'API, initialisez une instance de client. Pour les instructions de configuration, consultez la rubrique Initialisation.

Soumettre une tâche de transcodage

Appelez l'opération SubmitTranscodeJobs pour soumettre une tâche de transcodage. L'exemple suivant montre comment :

  • Définir l'ID vidéo et l'ID du groupe de modèles de transcodage

  • Remplacer les paramètres de filigrane (facultatif)

  • Configurer le chiffrement HTTP Live Streaming (HLS) (facultatif)

  • Extraire l'ID de tâche de la réponse

Seules les vidéos à l'état Uploaded , Normal ou Reviewing peuvent être transcodées. Configurez les paramètres de rappel pour recevoir les notifications d'événement FileUploadComplete ou ImageUploadComplete , puis soumettez les tâches de transcodage une fois le téléchargement terminé. Pour recevoir les résultats de transcodage, abonnez-vous à l'événement StreamTranscodeComplete ou TranscodeComplete . Pour plus de détails, consultez la rubrique Configurer les paramètres de rappel .
import com.aliyuncs.vod.model.v20170321.SubmitTranscodeJobsRequest;
import com.aliyuncs.vod.model.v20170321.SubmitTranscodeJobsResponse;

/**
 * Submit a transcoding job with optional watermark overrides and HLS encryption.
 */
public static SubmitTranscodeJobsResponse submitTranscodeJobs(DefaultAcsClient client) throws Exception {
    SubmitTranscodeJobsRequest request = new SubmitTranscodeJobsRequest();

    // TODO: Replace with your video ID
    request.setVideoId("34a6ca54f5c140eece85a289****");

    // TODO: Replace with your transcoding template group ID
    request.setTemplateGroupId("e8aa925a9798c630d30cd****");

    // Override watermark parameters (optional). Required only to change watermark content at submission time.
    JSONObject overrideParams = buildOverrideParams();
    request.setOverrideParams(overrideParams.toJSONString());

    // Configure HLS encryption (optional). Required only for HLS-encrypted outputs.
    JSONObject encryptConfig = buildEncryptConfig(client);
    request.setEncryptConfig(encryptConfig.toJSONString());

    return client.getAcsResponse(request);
}

/**
 * Entry point for the transcoding job example.
 */
public static void main(String[] args) throws ClientException {
    // Initialize the client. See the Initialization topic for details.
    DefaultAcsClient client = initVodClient();
    SubmitTranscodeJobsResponse response = new SubmitTranscodeJobsResponse();
    try {
        response = submitTranscodeJobs(client);
        // Extract the job ID for tracking
        System.out.println("JobId = " + response.getTranscodeJobs().get(0).getJobId());
    } catch (Exception e) {
        System.out.println("ErrorMessage = " + e.getLocalizedMessage());
    }
    // The request ID is useful for troubleshooting with Alibaba Cloud support
    System.out.println("RequestId = " + response.getRequestId());
}

Pour obtenir des détails complets sur l'API, consultez SubmitTranscodeJobs dans OpenAPI Explorer.

Remplacer les paramètres de filigrane

Remplacez l'URL d'un filigrane image ou le contenu d'un filigrane texte au moment de la soumission de la tâche. Chaque filigrane est identifié par un WatermarkId associé au modèle de transcodage spécifié par TemplateGroupId.

Le fichier de filigrane et la vidéo doivent être stockés sur le même serveur d'origine.
/**
 * Build watermark override parameters.
 *
 * Overridable fields:
 * - Image watermark: FileUrl (the OSS URL of the replacement image)
 * - Text watermark: Content (the replacement text)
 *
 * The WatermarkId must be associated with the transcoding template in use.
 */
public static JSONObject buildOverrideParams() {
    JSONObject overrideParams = new JSONObject();
    JSONArray watermarks = new JSONArray();

    // Override an image watermark URL
    JSONObject watermark1 = new JSONObject();
    // TODO: Replace with your image watermark ID (must be associated with the transcoding template)
    watermark1.put("WatermarkId", "2ea587477c5a1bc8b57****");
    // TODO: Replace with the Object Storage Service (OSS) URL of the new watermark image
    watermark1.put("FileUrl", "http://developer.aliyundoc.com/image/image.png");
    watermarks.add(watermark1);

    // Override a text watermark
    JSONObject watermark2 = new JSONObject();
    // TODO: Replace with your text watermark ID (must be associated with the transcoding template)
    watermark2.put("WatermarkId", "d297ba31ac5242d207****");
    // TODO: Replace with the new text content for the watermark
    watermark2.put("Content", "User ID: 6****");
    watermarks.add(watermark2);

    overrideParams.put("Watermarks", watermarks);
    return overrideParams;
}

Configurer le chiffrement HLS

Générez une clé de données Key Management Service (KMS) et construisez la configuration de chiffrement pour la sortie HLS. DecryptKeyUri spécifie le point de terminaison de votre service de déchiffrement. ApsaraVideo VOD appelle ce point de terminaison pendant la lecture pour récupérer la clé de déchiffrement.

import com.aliyuncs.vod.model.v20170321.GenerateKMSDataKeyRequest;
import com.aliyuncs.vod.model.v20170321.GenerateKMSDataKeyResponse;

/**
 * Build HLS encryption configuration using a KMS data key.
 */
public static JSONObject buildEncryptConfig(DefaultAcsClient client) throws ClientException {
    // Generate a KMS data key. The response contains both plaintext and ciphertext.
    // Only the ciphertext is passed to ApsaraVideo VOD.
    GenerateKMSDataKeyResponse response = generateDataKey(client);

    JSONObject encryptConfig = new JSONObject();

    // The URI of your decryption service. Concatenate the service URL with the ciphertext key.
    // The ciphertext is unique per video. The "Ciphertext" query parameter name is customizable.
    // TODO: Replace the base URL with your decryption service endpoint
    encryptConfig.put("DecryptKeyUri", "http://example.aliyundoc.com/decrypt?" +
            "Ciphertext=" + response.getCiphertextBlob());

    // Key service type. Only KMS is supported.
    encryptConfig.put("KeyServiceType", "KMS");

    // The ciphertext blob from the KMS GenerateDataKey response
    encryptConfig.put("CipherText", response.getCiphertextBlob());

    return encryptConfig;
}

/**
 * Generate a KMS data key for encryption.
 * The response contains the plaintext key (for internal use) and the ciphertext key
 * (passed to ApsaraVideo VOD for storage).
 */
public static GenerateKMSDataKeyResponse generateDataKey(DefaultAcsClient client) throws ClientException {
    GenerateKMSDataKeyRequest request = new GenerateKMSDataKeyRequest();
    return client.getAcsResponse(request);
}

Soumettre une tâche de capture d'images

Appelez l'opération SubmitSnapshotJob pour capturer des images de trames vidéo et générer un sprite (image sprite).

Pour créer un modèle de capture, consultez AddVodTemplate .
import com.aliyuncs.vod.model.v20170321.SubmitSnapshotJobRequest;
import com.aliyuncs.vod.model.v20170321.SubmitSnapshotJobResponse;

/**
 * Submit a snapshot job with optional sprite configuration.
 */
public static SubmitSnapshotJobResponse submitSnapshotJob(DefaultAcsClient client) throws Exception {
    SubmitSnapshotJobRequest request = new SubmitSnapshotJobRequest();

    // TODO: Replace with the video ID to capture snapshots from
    request.setVideoId("4d237a8270084849bf4207876181****");

    // TODO: Replace with your snapshot template ID.
    // When SnapshotTemplateId is specified, the individual parameters below are ignored.
    request.setSnapshotTemplateId("5d745e6b8baadf589e0702426cfc6****");

    // The following parameters apply only when SnapshotTemplateId is not specified.
    request.setCount(50L);               // Total number of snapshots to capture
    request.setSpecifiedOffsetTime(0L);   // Start time in milliseconds
    request.setInterval(1L);              // Interval between snapshots in seconds
    request.setWidth("200");              // Snapshot width in pixels
    request.setHeight("200");             // Snapshot height in pixels

    // Configure sprite generation (optional)
    JSONObject spriteSnapshotConfig = buildSnapshotTemplateConfig();
    request.setSpriteSnapshotConfig(spriteSnapshotConfig.toJSONString());

    return client.getAcsResponse(request);
}

/**
 * Entry point for the snapshot job example.
 */
public static void main(String[] args) throws ClientException {
    DefaultAcsClient client = initVodClient();
    SubmitSnapshotJobResponse response = new SubmitSnapshotJobResponse();
    try {
        response = submitSnapshotJob(client);
        // Extract the snapshot job ID for tracking
        System.out.println("JobId = " + response.getSnapshotJob().getJobId());
    } catch (Exception e) {
        System.out.println("ErrorMessage = " + e.getLocalizedMessage());
    }
    System.out.println("RequestId = " + response.getRequestId());
}

Pour obtenir des détails complets sur l'API, consultez SubmitSnapshotJob dans OpenAPI Explorer.

Configurer un sprite

Construisez les paramètres de configuration du sprite pour assembler les captures individuelles en une image en grille.

/**
 * Build sprite configuration.
 * A sprite arranges individual snapshots in a grid layout for efficient previewing.
 */
public static JSONObject buildSnapshotTemplateConfig() {
    JSONObject spriteSnapshotConfig = new JSONObject();
    spriteSnapshotConfig.put("CellWidth", "120");    // Width of each cell in pixels
    spriteSnapshotConfig.put("CellHeight", "68");     // Height of each cell in pixels
    spriteSnapshotConfig.put("Columns", "3");         // Number of columns in the grid
    spriteSnapshotConfig.put("Lines", "10");           // Number of rows in the grid
    spriteSnapshotConfig.put("Padding", "20");         // Padding between cells in pixels
    spriteSnapshotConfig.put("Margin", "50");          // Outer margin in pixels
    // Retain individual snapshot images after sprite generation.
    // Set to "keep" to preserve source images, or omit to discard them.
    spriteSnapshotConfig.put("KeepCellPic", "keep");
    spriteSnapshotConfig.put("Color", "tomato");       // Background color of the sprite
    return spriteSnapshotConfig;
}

Interroger les données de capture

Appelez l'opération ListSnapshots pour interroger les données de capture.

Pour obtenir des détails complets sur l'API et un exemple de code, consultez ListSnapshots dans OpenAPI Explorer.

Prétraiter les vidéos dans le studio de production

Appelez l'opération SubmitPreprocessJobs pour prétraiter les vidéos destinées au studio de production.

Pour obtenir des détails complets sur l'API et un exemple de code, consultez SubmitPreprocessJobs dans OpenAPI Explorer.

Étapes suivantes