Media processing transforms an audio or video file into one or more other audio or video files to suit different network bandwidths, devices, and user needs. It includes features such as video transcoding, video snapshots, and video watermarks. This topic provides API call examples that use the Python software development kit (SDK) for media processing. The examples cover how to submit transcoding jobs for scenarios such as HLS encryption, standard transcoding, and watermark replacement. The examples also cover how to submit snapshot jobs, query snapshot data, and preprocess videos in the production studio.
Usage notes
-
All examples in this topic use an AccessKey pair to initialize a client instance.
-
For request and response parameter details, visit Alibaba Cloud OpenAPI Explorer and open the API Documentations tab.
-
For SDK examples of other API operations, visit Alibaba Cloud OpenAPI Explorer. On the Parameters tab, specify the parameters and initiate the call. Then select the SDK version and language on the SDK Sample Code tab to view and download the code.
-
The examples in this topic use SDK V1.0. For V2.0 examples, select the correct SDK version in OpenAPI Explorer.
Initialize a client
Before you use the SDK, initialize a client. For more information, see Initialization.
Submitting a Standard Transcoding Job
Call the SubmitTranscodeJobs API to generate sample SDK code for submitting a standard transcoding job.
Alibaba cloud OpenAPI portal address:SubmitTranscodeJobs.
Sample code:
The following code provides an example on transcoding without encryption. For more information about video encryption supported by Alibaba Cloud, see Alibaba Cloud proprietary cryptography.
"""
* Construct watermark parameters to be overridden. You can override only the URL of an image watermark and the content of a text watermark.
* Make sure that the ID of the watermark that you want to overwrite is associated with the ID of the transcoding template that you use. The ID of the transcoding template is specified by TranscodeTemplateId.
* You can call this operation to add only a watermark whose ID is associated with the ID of the transcoding template that you use.
"""
def build_override_params():
# Override watermarks.
watermarks = []
// Override an image watermark. Example of the URL of an image file: https://192.168.0.0/16/watermarks/sample****.png.
watermark1 = {'WatermarkId': '<watermarkId>', 'FileUrl': '<your File URL>'}
watermarks.append(watermark1)
# Override a text watermark.
watermark2 = {'WatermarkId': '<watermarkId>', 'Content': 'new Text'}
watermarks.append(watermark2)
return {'Watermarks': watermarks}
""" Start transcoding. """
from aliyunsdkvod.request.v20170321 import SubmitTranscodeJobsRequest
def normal_submit_transcode_jobs(clt):
request = SubmitTranscodeJobsRequest.SubmitTranscodeJobsRequest()
# Specify the ID of the video that you want to transcode.
request.set_VideoId('<videoId>')
# Specify the transcoding template group.
request.set_TemplateGroupId('<templateGroupId>')
"""
# Configure optional parameters to overwrite watermarks.
overrideParams = build_override_params()
request.set_OverrideParams(json.dumps(overrideParams))
"""
request.set_accept_format('JSON')
response = json.loads(clt.do_action_with_exception(request))
return response
try:
clt = init_vod_client()
jobs = normal_submit_transcode_jobs(clt)
print(jobs['TranscodeJobs']['TranscodeJob'])
print(json.dumps(jobs, ensure_ascii=False, indent=4))
except Exception as e:
print(e)
print(traceback.format_exc())Submit a transcoding job with HLS encryption enabled
You can call the SubmitTranscodeJobs operation to submit a transcoding job with HLS encryption enabled.
Alibaba cloud OpenAPI portal address:SubmitTranscodeJobs.
Sample code:
The following code provides an example on transcoding with HLS encryption enabled. For more information, see HLS encryption.
"""
* Optional configurations of HLS encryption. If you do not use HLS encryption, these configurations are not required.
"""
from aliyunsdkvod.request.v20170321 import GenerateKMSDataKeyRequest
from aliyunsdkcore.http import protocol_type
def build_encrypt_config(clt):
try:
# Generate a random data key for encryption. The response contains the plaintext and ciphertext of the data key.
# Specify only the ciphertext for HLS encryption.
request = GenerateKMSDataKeyRequest.GenerateKMSDataKeyRequest()
request.set_protocol_type(protocol_type.HTTPS)
request.set_accept_format('JSON')
response = json.loads(clt.do_action_with_exception(request))
// The URI of the operation that is used to decrypt the data key. To obtain the URI, concatenate the URL of the decryption service and the ciphertext of the data key. The ciphertext to decrypt varies among videos. Take note that you must deploy the decryption service.
# You can customize the name of the Ciphertext parameter. The name in this example is only for reference.
# Example of decryptKeyUri: http://example.aliyundoc.com/decrypt?' + 'Ciphertext=' + response['CiphertextBlob.
decryptKeyUri = ['<your decryptKeyUri>']
return {'DecryptKeyUri': decryptKeyUri, 'KeyServiceType': 'KMS', 'CipherText': response['CiphertextBlob']}
except Exception as e:
print(e)
#print(traceback.format_exc())
return None
""" Start transcoding. """
from aliyunsdkvod.request.v20170321 import SubmitTranscodeJobsRequest
def hlsencrypt_submit_transcode_jobs(clt):
request = SubmitTranscodeJobsRequest.SubmitTranscodeJobsRequest()
# Specify the ID of the video that you want to transcode.
request.set_VideoId('<videoId>')
# Specify the transcoding template group.
request.set_TemplateGroupId('<templateGroupId>')
# Use Key Management Service (KMS) to generate a random encryption key.
encryptConfig = build_encrypt_config(clt)
if encryptConfig is not None:
request.set_EncryptConfig(json.dumps(encryptConfig))
request.set_accept_format('JSON')
response = json.loads(clt.do_action_with_exception(request))
return response
try:
clt = init_vod_client()
jobs = hlsencrypt_submit_transcode_jobs(clt)
print(jobs['TranscodeJobs']['TranscodeJob'])
print(json.dumps(jobs, ensure_ascii=False, indent=4))
except Exception as e:
print(e)
print(traceback.format_exc())Submit a snapshot job
You can call the SubmitSnapshotJob operation to submit a snapshot job.
Alibaba cloud OpenAPI portal address:SubmitTranscodeJobs.
Sample code:
For more information about how to create a snapshot template, see Create a snapshot template.
from aliyunsdkvod.request.v20170321 import SubmitSnapshotJobRequest
def submit_snapshot_job(clt):
request = SubmitSnapshotJobRequest.SubmitSnapshotJobRequest()
# Specify the ID of the video from which you want to capture snapshots.
request.set_VideoId('<videoId>')
# Specify the ID of the snapshot template.
#request.set_SnapshotTemplateId('<snapshotTemplateId>')
# If you specify the ID of the snapshot template, the following parameters are ignored:
request.set_Count(50)
request.set_SpecifiedOffsetTime(0)
request.set_Interval(1)
request.set_Width(200)
request.set_Height(200)
# Configure image sprite-related parameters. This step is optional.
spriteSnapshotConfig = {'CellWidth': 120, 'CellHeight': 68, 'Columns': 3,
'Lines': 10, 'Padding': 20, 'Margin': 50}
# Specify whether to retain the source image after an image sprite is generated.
spriteSnapshotConfig['KeepCellPic'] = 'keep'
spriteSnapshotConfig['Color'] = 'tomato'
request.set_SpriteSnapshotConfig(json.dumps(spriteSnapshotConfig))
request.set_accept_format('JSON')
response = json.loads(clt.do_action_with_exception(request))
return response
try:
clt = init_vod_client()
job = submit_snapshot_job(clt)
print(json.dumps(job, ensure_ascii=False, indent=4))
except Exception as e:
print(e)
print(traceback.format_exc())Query snapshot data
You can call the ListSnapshots operation to query snapshot data.
Alibaba cloud OpenAPI portal address:SubmitTranscodeJobs.
Preprocess videos in the production studio
You can call the SubmitPreprocessJobs operation to preprocess videos in the production studio.
Alibaba cloud OpenAPI portal address:SubmitTranscodeJobs.
Related Documents
Media processing:Describes the media processing capabilities provided by ApsaraVideo for VOD, including capability types, usage scenarios, and details of each media processing capability.
Transcoding FAQ:This section describes the common problems and handling suggestions in the process of using video on demand transcoding.