Todos os produtos
Search
Central de documentação

Intelligent Media Services:Script-to-Video

Última atualização: Jul 03, 2026

Conheça os parâmetros de produção, as configurações avançadas e os exemplos de SDK para Script-to-Video.

Importante
  • Tanto o Script-to-Video quanto o Image-Text Matching utilizam a API SubmitBatchMediaProducingJob para enviar uma tarefa. Para diferenciá-los com base nos parâmetros, consulte Diferenças de parâmetros.

  • Nesta API, a região especificada na URL do OSS de todos os ativos de mídia deve ser idêntica ao endpoint de serviço da OpenAPI.

  • Regiões compatíveis: China (Shanghai), China (Beijing), China (Hangzhou), China (Shenzhen), EUA (Silicon Valley) e Singapura.

  • Na prática, substitua todos os espaços reservados nos exemplos, como [your-bucket], [your-region-id], [your-file-name], [your-file-path] e IDs de ativos de mídia ("**9d46c8b4548681030f6e**"), pelos seus valores reais.

Nota
  • Para compreender melhor este documento, leia primeiro o guia de Produção de vídeo em lote e familiarize-se com os conceitos e o fluxo de trabalho do Script-to-Video.

  • O Script-to-Video oferece dois modos de produção: Global Scripts e Segmented Scripts.

    • Global Scripts: Combina aleatoriamente vários roteiros completos de narração com ativos de vídeo para gerar um grande volume de vídeos com estilo semelhante.

    • Segmented Scripts: Divide um roteiro de narração em múltiplos segmentos e associa cada segmento a um grupo específico de ativos.

    • A definição do modo segue a lógica de parâmetros abaixo:

Observações de uso

  • Para enviar um trabalho de produção de vídeo em lote que mistura inteligentemente vários ativos de vídeo, áudio e imagem, consulte SubmitBatchMediaProducingJob. Os principais parâmetros da API estão detalhados nas seções InputConfig, EditingConfig e OutputConfig abaixo.

  • Para obter informações detalhadas sobre um trabalho de criação de vídeo em lote, acesse GetBatchMediaProducingJob.

InputConfig

O InputConfig define os ativos básicos: clipes de vídeo, narrações, música de fundo e adesivos.

Parâmetro

Tipo

Descrição

Exemplo

Obrigatório

Modos compatíveis

MediaGroupArray

List<MediaGroup>

Especifica os ativos de source. Permite agrupar ativos.

Nome do grupo: Até 50 caracteres. Não aceita emojis.

Lista de materiais: ID do ativo de mídia ou URL do OSS do material.

Aceita no máximo 40 grupos, cada um contendo até 200 materiais.

Exemplo: Modo Global Scripts

Exemplo: Modo Segmented Scripts

Sim

  • Global Scripts

  • Segmented Scripts

TitleArray

List<String>

Um array de títulos. O sistema seleciona aleatoriamente um título para cada produção.

Máximo de 50 títulos, cada um com até 50 caracteres.

["Title 1","Title 2"]

Não

  • Global Scripts

  • Segmented Scripts

SubHeadingArray

List<SubHeading>

Configurações de subtítulos multinível.

[{"Level":1,"TitleArray":["Level 1 subtitle 1","Level 1 subtitle 2"]},{"Level":3,"TitleArray":["Level 3 subtitle"]}]

Não

  • Global Scripts

  • Segmented Scripts

SpeechTextArray

List<String>

  • Um array de roteiros de narração. Um roteiro é selecionado aleatoriamente para cada produção.

  • Máximo de 50 roteiros, cada um com até 1000 caracteres.

  • Permite controlar a síntese de fala usando SSML.

  • O idioma padrão é chinês (zh). Para definir outros idiomas, consulte SpeechLanguage.

    Importante

    Atualmente, apenas <break>, <s>, <sub>, <w>, <phoneme> e <say-as> são compatíveis.

["Voiceover content 1","Voiceover content 2"]

Não

  • Global Scripts

StickerArray

List<Sticker>

  • Um array de adesivos. Um adesivo é selecionado aleatoriamente para cada produção. Máximo de 50 adesivos.

  • Regra de seleção: Se você fornecer 10 adesivos e solicitar 20 vídeos, o sistema escolherá um índice inicial aleatório (por exemplo, 3) e selecionará os adesivos ciclicamente: 3, 4, 5, ..., 10, 1, 2, 3, ...

  • Para formatos compatíveis, consulte Formatos de imagem.

[{"MediaId":"**9d46c8b4548681030f6e**","X":10,"Y":100,"Width":300,"Height":300,"Opacity":0,6}]

Não

  • Global Scripts

  • Segmented Scripts

BackgroundMusicArray

List<String>

  • Um array de faixas de música de fundo. Uma faixa é selecionada aleatoriamente para cada produção. Máximo de 50 faixas. Aceita IDs de ativos de mídia ou URLs do OSS.

  • Regra de seleção: Funciona da mesma forma que o StickerArray.

  • Para formatos compatíveis, consulte Formatos de áudio.

["**b4549d46c88681030f6e","549d46c88b4681030f6e**"]

Não

  • Global Scripts

  • Segmented Scripts

BackgroundImageArray

List<String>

  • Um array de imagens de fundo. Uma imagem é selecionada aleatoriamente para cada produção. Máximo de 50 imagens. Aceita IDs de ativos de mídia ou URLs do OSS.

  • Regra de seleção: Funciona da mesma forma que o StickerArray.

  • Para formatos compatíveis, consulte Formatos de imagem.

["**b4549d46c88681030f6e","549d46c88b4681030f6e**"]

Não

  • Global Scripts

  • Segmented Scripts

MediaGroup

Nota

As diferenças de parâmetros do MediaGroup entre Global Scripts e Segmented Scripts aparecem na coluna Modos compatíveis.

Parâmetro

Tipo

Descrição

Exemplo

Obrigatório

Modos compatíveis

GroupName

String

Nome do grupo. Máximo de 50 caracteres, sem emojis.

Group1

Sim

  • Global Scripts

  • Segmented Scripts

MediaArray

List<String>

  • Uma lista de ativos, aceitando IDs de ativos de mídia ou URLs. Máximo de 200 ativos.

  • Para formatos compatíveis, consulte Formatos de vídeo.

**b4549d46c88681030f6e**

Sim

  • Global Scripts

  • Segmented Scripts

SpeechTextArray

List<String>

  • Um array de roteiros de narração. Um roteiro é selecionado aleatoriamente para cada produção.

  • Máximo de 50 roteiros, cada um com até 1000 caracteres.

  • Permite controlar a síntese de fala usando SSML.

    Importante

    Atualmente, apenas <break>, <s>, <sub>, <w>, <phoneme> e <say-as> são compatíveis.

["Voiceover content 1","Voiceover content 2"]

Não

  • Segmented Scripts

Duration

Float

Duração do grupo atual, em segundos. Utilize apenas quando SpeechTextArray estiver vazio.

10

Não. Padrão: 5.

  • Global Scripts

SplitMode

String

NoSplit

Não. Padrão: AverageSplit.

  • Global Scripts

  • Segmented Scripts

Volume

Float

  • Volume do vídeo de entrada para este grupo. Se definido, substitui EditingConfig.MediaConfig.Volume para este grupo.

  • Intervalo: [0, 10,0]. Aceita duas casas decimais.

0,5

Não

  • Global Scripts

DurationAutoAdapt

Boolean

Indica se a adaptação automática de duração deve ser ativada para este grupo. Quando ativado e não há narração, a duração do grupo é ajustada para garantir que os clipes de vídeo sejam reproduzidos na velocidade original.

true

Não. Padrão: false.

  • Global Scripts

Exemplo: Modo Global Scripts

{
  "MediaGroupArray": [
    {
      "GroupName": "UseMediaId",
      "MediaArray": [
        "****9d46c886b45481030f6e****",
        "****c886810b4549d4630f6e****"
      ],
      "SplitMode": "NoSplit"
    },
    {
      "GroupName": "UseOssUrl",
      "MediaArray": [
        "http://[your-bucket].oss-[your-region-id].aliyuncs.com/[your-file-path]/[your-file-name].mp4",
        "http://[your-bucket].oss-[your-region-id].aliyuncs.com/[your-file-path]/[your-file-name].png"
      ]
    }
  ],
  "TitleArray": [
    "Freshippo opens a new location in Huilongguan",
    "A new Freshippo store opens"
  ],
  "SubHeadingArray": [
    {
      "Level": 1,
      "TitleArray": ["Subtitle 1", "Subtitle 2"]
    },
    {
      "Level": 3,
      "TitleArray": ["Level 3 subtitle"]
    }
  ],
  "SpeechTextArray": [
    "A new Freshippo store just opened in the nearby mall. It's the grand opening today, so I rushed over to check it out. The store isn't huge, but it's packed with people. Snacks and drinks are pretty cheap, and the checkout lines are super long. Come and see for yourself!",
    "A new  Freshippo store just opened in the nearby mall. It's the grand opening today, so I rushed over to check it out.",
    "<speak>Today, our hero, table tennis legend <phoneme alphabet="ipa" ph="mɑː lʊŋ">Ma Long</phoneme>, is striving for the pinnacle of glory.</speak>"
  ],
  "StickerArray": [
    {
      "MediaId": "****9d46c8b4548681030f6e****",
      "X": 10,
      "Y": 100,
      "Width": 300,
      "Height": 300,
      "Opacity": 0.6
    },
    {
      "MediaURL": "http://[your-bucket].oss-[your-region-id].aliyuncs.com/[your-file-path]/[your-file-name].png",
      "X": 10,
      "Y": 100,
      "Width": 300,
      "Height": 300
    }
  ],
  "BackgroundMusicArray": [
    "****b4549d46c88681030f6e****",
    "****549d46c88b4681030f6e****",
    "http://[your-bucket].oss-[your-region-id].aliyuncs.com/[your-file-path]/[your-file-name].mp3"
  ],
  "BackgroundImageArray": [
    "****6c886b4549d481030f6e****",
    "****9d46c8548b4681030f6e****",
    "http://[your-bucket].oss-[your-region-id].aliyuncs.com/[your-file-path]/[your-file-name].png"
  ]
}

Exemplo: Segmented Scripts

{
  "MediaGroupArray": [{
    "GroupName": "start",
    "MediaArray": ["https://[your-bucket].oss-[your-region-id].aliyuncs.com/[your-file-path]/[your-file-name].jpeg", "https://[your-bucket].oss-[your-region-id].aliyuncs.com/[your-file-path]/[your-file-name].mp4"],
    "Duration": 5,
    "SplitMode": "NoSplit",
    "Volume": 1
  },
    {
      "GroupName": "group1",
      "MediaArray": ["https://[your-bucket].oss-[your-region-id].aliyuncs.com/[your-file-path]/[your-file-name].png", "https://[your-bucket].oss-[your-region-id].aliyuncs.com/[your-file-path]/[your-file-name].mp4"],
      "SpeechTextArray": ["A new Freshippo store just opened in the nearby mall.", "It's the grand opening today.", "<speak>Today, our hero, table tennis legend <phoneme alphabet="ipa" ph="mɑː lʊŋ">Ma Long</phoneme>, is striving for the pinnacle of glory.</speak>"]
    },
    {
      "GroupName": "group2",
      "MediaArray": ["https://[your-bucket].oss-[your-region-id].aliyuncs.com/0-test-batch-editing-materials/normal%20video.mp4", "https://[your-bucket].oss-[your-region-id].aliyuncs.com/[your-file-path]/[your-file-name].jpeg"],
      "SpeechTextArray": ["The store isn't huge, but it's packed with people. Snacks and drinks are pretty cheap, and the checkout lines are super long.", "The scene is very lively, with crowds of people and a wide variety of goods."]
    },
    {
      "GroupName": "group3",
      "MediaArray": ["https://[your-bucket].oss-[your-region-id].aliyuncs.com/0-test-batch-editing-materials/young_sunset_walk.mp4"],
      "SpeechTextArray": ["Come and see for yourself!", "Hurry and come take a look!"]
    },
    {
      "GroupName": "end",
      "MediaArray": ["https://[your-bucket].oss-[your-region-id].aliyuncs.com/[your-file-path]/[your-file-name].jpg", "https://[your-bucket].oss-[your-region-id].aliyuncs.com/[your-file-path]/[your-file-name].mp4"],
      "Duration": 5
    }
  ],
  "TitleArray": [
    "Freshippo opens a new location in Huilongguan",
    "A new Freshippo store opens"
  ],
  "StickerArray": [
    {
      "MediaId": "****9d46c8b4548681030f6e****",
      "X": 10,
      "Y": 100,
      "Width": 300,
      "Height": 300,
      "Opacity": 0.6
    },
     {
      "MediaURL": "http://[your-bucket].oss-[your-region-id].aliyuncs.com/[your-file-path]/[your-file-name].png",
      "X": 10,
      "Y": 100,
      "Width": 300,
      "Height": 300
    }
  ],
  "SubHeadingArray": [
    {
      "Level": 1,
      "TitleArray": ["Level 1 subtitle 1", "Level 1 subtitle 2"]
    },
    {
      "Level": 3,
      "TitleArray": ["Level 3 subtitle"]
    }
  ],
  "BackgroundMusicArray": [
    "****b4549d46c88681030f6e****",
    "****549d46c88b4681030f6e****",
    "http://[your-bucket].oss-[your-region-id].aliyuncs.com/[your-file-path]/[your-file-name].mp3"
  ],
  "BackgroundImageArray": [
    "****6c886b4549d481030f6e****",
    "****9d46c8548b4681030f6e****",
    "http://[your-bucket].oss-[your-region-id].aliyuncs.com/[your-file-path]/[your-file-name].png"
  ]
}

EditingConfig

O EditingConfig especifica volume, posicionamento e outras configurações de produção.

Nota

Todos os parâmetros são compatíveis com os modos Global Scripts e Segmented Scripts, exceto:

Parâmetro

Tipo

Descrição

Exemplo

Obrigatório

MediaConfig

JSON

Configuração do ativo de vídeo de entrada.

{"Volume":"1","MediaMetaDataArray":[{"Media":"**6c886b4549d481030f6e**","GroupName":"GroupA","TimeRangeList":[{"In":"0","Out":"1"},{"In":"2","Out":"3"}]}]}

Não

TitleConfig

JSON

Configuração para títulos.

{"Alignment":"TopCenter","AdaptMode":"AutoWrap","Font":"Alibaba PuHuiTi 2.0 95 ExtraBold","SizeRequestType":"Nominal","Y":0.1}

Não

SubHeadingConfig

JSON

Configuração para subtítulos multinível.

Campos JSON:

{"1":{"Y":0.3,"FontSize":40},"3":{"Y":0.5,"FontSize":30}}

Não

SpeechConfig

JSON

Configuração da narração.

Consulte Exemplos de parâmetros do EditingConfig

Não

BackgroundMusicConfig

JSON

Configuração da música de fundo.

{"Volume":0.2}

Não

BackgroundImageConfig

JSON

Configuração da imagem de fundo. Ignorado se uma imagem de fundo já estiver definida no InputConfig.

{"SubType":"Blur","Radius":0.5}

Não

ProcessConfig

JSON

Configuração do processo de mixagem e edição.

Consulte Exemplos de parâmetros do EditingConfig

Não

FECanvas

JSON

Configuração de canvas para visualização front-end.

{"Width": 1080,"Height": 1920}

Não

ProduceConfig

JSON

Configuração padrão de edição e produção. Para campos, consulte EditingProduceConfig.

{"AutoRegisterInputVodMedia":true,"OutputWebmTransparentChannel":true,"CoverConfig":{"StartTime":3.3},"AudioChannelCopy":"left","PipelineId":"**d54a97cff4108b555b01166d4**","MaxBitrate":5000,"KeepOriginMaxBitrate":false,"KeepOriginVideoMaxFps":false}

Não

ProcessConfig

Parâmetro

Tipo

Descrição

Exemplo

Obrigatório

SingleShotDuration

Float

Duração de cada plano segmentado automaticamente ao dividir ativos de vídeo longos, em segundos.

5

Não. Padrão: 3.

AllowVfxEffect

Boolean

Indica se efeitos especiais devem ser adicionados.

true

Não. Padrão: false.

VfxEffectProbability

Float

Probabilidade de aplicar um efeito a cada clipe. Intervalo: 0,0–1,0. Aceita 2 casas decimais.

0,6

Não. Padrão: 0,5.

VfxFirstClipEffectList

List<String>

  • Se não estiver vazio, o efeito para o primeiro clipe do vídeo será escolhido desta lista.

  • Se estiver vazio, um efeito aleatório é escolhido entre os seguintes padrões: slightshow, starfieldshinee, starfieldshinee2, starsparkle, colorfulripples, starfield.

  • Para exemplos de efeitos, consulte Exemplos de efeitos especiais.

["slightshow","starfieldshinee"]

Não

VfxNotFirstClipEffectList

List<String>

  • Se não estiver vazio, os efeitos para todos os clipes, exceto o primeiro, serão escolhidos desta lista.

  • Se estiver vazio, um efeito aleatório é escolhido entre os seguintes padrões: zoomslight, zoom, zoominout, slightshake.

  • Para exemplos de efeitos, consulte Exemplos de efeitos especiais.

["zoomslight","zoom"]

Não

AllowTransition

Boolean

Indica se efeitos de transição devem ser adicionados.

true

Não. Padrão: false.

TransitionDuration

Float

Duração das transições em segundos. Se TransitionDuration > ClipDuration - 1, a transição para esse clipe não será aplicada.

0,5

Não. Padrão: 0,5.

TransitionList

List<String>

Uma lista de transições personalizadas. Se AllowTransition for true, uma transição aleatória desta lista será usada. Para transições disponíveis, consulte Efeitos de transição. Se esta lista estiver vazia, uma transição aleatória é escolhida entre: linearblur, colordistance, crosshatch, dreamyzoom, doomscreentransition_up.

["directional", "linearblur"]

Não

UseUniformTransition

Boolean

Indica se a mesma transição deve ser usada em todo o vídeo.

true

Não. Padrão: true.

AllowFilter

Boolean

Indica se filtros personalizados devem ser adicionados.

false

Não. Padrão: false.

FilterList

List<String>

Uma lista de filtros personalizados. Se AllowFilter for true, um filtro aleatório desta lista é aplicado. Para filtros disponíveis, consulte Filtros. Se esta lista estiver vazia, nenhum filtro é aplicado.

["m1", "m2"]

Não

AlignmentMode

String

Modo de alinhamento para vídeo e narração. Válido apenas no modo Global Scripts.

Valores válidos:

  • AutoSpeed: A duração da faixa de vídeo é ajustada para corresponder à faixa de áudio.

  • Cut: A faixa de vídeo é truncada para corresponder à faixa de áudio.

AutoSpeed

Não. Padrão: AutoSpeed.

ImageDuration

Float

Duração dos ativos de imagem estática, em segundos.

2

Não. Padrão: 2.

Exemplo de parâmetro

{
  "MediaConfig": {
    "Volume": 0 // Input video assets are muted by default
  },
  "TitleConfig": {
    "Alignment": "TopCenter",
    "AdaptMode": "AutoWrap",
    "Font": "Alibaba PuHuiTi 2.0 95 ExtraBold",
    "SizeRequestType": "Nominal",
    "Y": 0.1, // Y-coordinate for portrait video
    "Y": 0.05, // Y-coordinate for landscape video
    "Y": 0.08 // Y-coordinate for square video
  },
   "SubHeadingConfig": {
    "1": {
      "Y": 0.3,
      "FontSize": 40
    },
    "3": {
      "Y": 0.5,
      "FontSize": 30
    }
  },
  "SpeechConfig": {
    "Volume": 1,  // Voiceover uses original volume by default
    "SpeechRate": 0,
    "Voice": null,
    "Style": null,
    "CustomizedVoice": null, // Voice ID. If set, Voice and Style are ignored.
    "AsrConfig": {
      "Alignment": "TopCenter",
      "AdaptMode": "AutoWrap",
      "Font": "Alibaba PuHuiTi 2.0 65 Medium",
      "SizeRequestType": "Nominal",
      "Spacing": -1,
      "Y": 0.8, // Subtitle Y-coordinate for portrait video
      "Y": 0.9, // Subtitle Y-coordinate for landscape video
      "Y": 0.85 // Subtitle Y-coordinate for square video
    },
    "SpecialWordsConfig": [{
      "Type": "Highlight",
      "Style": {
        "FontName": "KaiTi",
        "FontSize": 80,
        "FontColor": "20AEE9",
        "OutlineColour": "2D20E9",
        "Outline": 3,
        "FontFace": {
          "Bold": true,
          "Underline": true
        }
      },
      "WordsList": [
        "ApsaraVideo",
        "Intelligent Media Services",
        "Batch video creation"
      ]
    },
    {
      "Type": "Highlight",
      "Style": {
        "FontFace": {
          "Italic": true
        }
      },
      "WordsList": [
        "product",
        "take a look"
      ]
    },
    {
      "Type": "Forbidden",
      "WordsList": [
        "pilipala",
        "bilibala"
      ],
      "SoundReplaceMode": "None"
    }
  ]},
  "BackgroundMusicConfig": {
    "Volume": 0.2,   // Background music at 20% volume by default
    "Style": null
  },
  "ProcessConfig": {
    "SingleShotDuration": 3,      // Duration of a shot after splitting
    "AllowVfxEffect": false,	  // Specifies whether to add special effects
    "AllowTransition": false,	  // Specifies whether to add transition effects
    "AlignmentMode": "AutoSpeed"  // This field is supported only in Global Scripts mode
  }
}

TemplateConfig

O TemplateConfig contém parâmetros comuns para produção de vídeo em lote. Para parâmetros detalhados e exemplos, consulte TemplateConfig.

Parâmetros do OutputConfig

O OutputConfig especifica o destino de saída, convenções de nomenclatura, resolução e quantidade de vídeos.

Os parâmetros aplicam-se a ambos os modos.

Parâmetro

Tipo

Descrição

Exemplo

Obrigatório

MediaURL

String

URL do vídeo de saída. Deve incluir o espaço reservado {index}.

Regra: http://[your-bucket].oss-[your-region-id].aliyuncs.com/[your-file-path]/[your-file-name]_{index}.mp4

Exemplo: http://example.oss-cn-shanghai.aliyuncs.com/example/example_{index}.mp4

Obrigatório se GeneratePreviewOnly for falso e a saída for para o OSS.

StorageLocation

String

Local de armazenamento para ativos de mídia enviados ao ApsaraVideo VOD.

Regra: [your-vod-bucket].oss-[your-region-id].aliyuncs.com

Exemplo: outin-**6c886b4549d481030f6e**.oss-cn-shanghai.aliyuncs.com

Obrigatório se GeneratePreviewOnly for falso e a saída for para o VOD.

FileName

String

Nome do arquivo de saída. Deve incluir o espaço reservado {index}.

Regra: [your-file-name]__{index}.mp4

Exemplo: example_{index}.mp4

Obrigatório se GeneratePreviewOnly for falso e a saída for para o VOD.

GeneratePreviewOnly

Boolean

  • Se verdadeiro, o trabalho gera apenas uma linha do tempo de pré-visualização, sem produzir efetivamente um vídeo. A URL de saída não é necessária.

  • Após a conclusão do trabalho, consulte o resultado usando GetBatchMediaPoducingJob para obter o ID do projeto de edição (projectId) e, em seguida, chame GetEditingProject para recuperar a linha do tempo de pré-visualização.

false

Não. Padrão: false.

Count

Integer

Número de vídeos a serem gerados. Máximo: 100.

10

Não. Padrão: 1.

MaxDuration

Float

Duração máxima por vídeo de saída, em segundos.

20

Não. Padrão: 15.

FixedDuration

Float

Duração fixa por vídeo de saída. Se definido, a duração do vídeo ajusta-se a este valor.

  • Não compatível com o modo Segmented Scripts.

  • No modo Global Scripts, este parâmetro é compatível quando SpeechTextArray está vazio.

  • Defina FixedDuration ou MaxDuration.

  • Regras de duração do vídeo.

20

Não. Padrão: 15.

Width

Integer

Largura do vídeo de saída, em pixels.

1080

Sim

Height

Integer

Altura do vídeo de saída, em pixels.

1920

Sim

Video

JSON

Configuração do fluxo de vídeo de saída (CRF, codec, etc.).

{"Crf": 27}

Não

Exemplo de parâmetro

{
 	"MediaURL": "http://[your-bucket].oss-[your-region-id].aliyuncs.com/[your-file-path]/[your-file-name]_{index}.mp4",
 	"Count": 20,
 	"MaxDuration": 15,
 	"Width": 1080,
 	"Height": 1920,
 	"Video": {"Crf": 27},
        "GeneratePreviewOnly":false
}

Aplicações

Exemplo 1: Configure introdução e encerramento com o modo Segmented Scripts

Caso de uso

Adicione uma introdução e um encerramento consistentes definindo MediaGroup.SplitMode como NoSplit para o primeiro e o último grupos. Dessa forma, o sistema reproduz integralmente um ativo selecionado aleatoriamente desses grupos.

Código de exemplo

Clique em para ver o exemplo de InputConfig

{
    "mediaGroupArray": [
        {
            "duration": 4,
            "splitMode": "NoSplit",
            "groupName": "opening",
            "mediaArray": [
                "****e44009ee71f0b62bf6f7d44b****"
            ]
        },
        {
            "groupName": "group1",
            "mediaArray": [
                "****e44009eef1f0b62bf6f7d44b****"
            ],
            "speechTextArray": [
                "Wondering where to go for the holiday?",
                "Still hesitant about your holiday plans?"
            ]
        },
        {
            "groupName": "group2",
            "mediaArray": [
                "****e44009eeferfb62bf6f7d44b****",
                "****e440094fghf0b62bf6f7d44b****",
                "****e44009ee74fgh62bf6f7d44b****"
            ],
            "speechTextArray": [
                "Lugu Lake in Yunnan invites you for a date with nature. The azure lake is like a mirror, reflecting the unique customs of the Mosuo Kingdom of Women, as picturesque as a painting.",
                "Why not consider a natural feast at Lugu Lake in Yunnan? The azure, mirror-like lake reflects the unique folk customs of the Mosuo Kingdom of Women, picturesque and fascinating."
            ]
        },
        {
            "groupName": "group3",
            "mediaArray": [
                "****e44009ee7ft5662bf6f7d44b****"
            ],
            "speechTextArray": [
                "Come to Lugu Lake and share this quiet and charming landscape!",
                "Share the endless poetry brought by this quiet and charming landscape!"
            ]
        },
        {
            "duration": 4,
            "splitMode": "NoSplit",
            "groupName": "ending",
            "mediaArray": [
                "****e44009ee5fgfg62bf6f7d44b****"
            ]
        }
    ]
}

Clique em para ver o exemplo de EditingConfig

{
    "MediaConfig": {
        "MediaMetaDataArray": [
            {
                "Media": "****e44009eedttg62bf6f7d44b****",
                "GroupName": "opening",
                "TimeRangeList": [
                    {
                        "In": 1.5,
                        "Out": 5.5
                    }
                ]
            },
            {
                "Media": "****e44009ee7dfrf62bf6f7d44b****",
                "GroupName": "ending",
                "TimeRangeList": [
                    {
                        "In": 1.5,
                        "Out": 5.5
                    }
                ]
            }
        ]
    }
}

Clique em para ver o exemplo de OutputConfig

{
    "count": 10,
    "height": 1920,
    "mediaURL": "http://[your-bucket].oss-[your-region-id].aliyuncs.com/[your-file-path]/[your-file-name]_{index}.mp4",
    "width": 1080,
    "widthHeightRatio": 0.5625
}

Exemplo 2: Crie um vídeo de montagem de rostos

Melhores práticas para criar vídeos de montagem de rostos.

Exemplo de SDK

Pré-requisitos

Você instalou o SDK do servidor IMS. Para mais informações, consulte Introdução.

Exemplo de código

Este exemplo utiliza o modo Global Scripts.

Expanda para ver o exemplo de código

package com.example;

import java.util.*;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.aliyun.ice20201109.Client;
import com.aliyun.ice20201109.models.*;
import com.aliyun.teaopenapi.models.Config;

/**
 *  You need to add the following Maven dependencies:
 *   <dependency>
 *      <groupId>com.aliyun</groupId>
 *      <artifactId>ice20201109</artifactId>
 *      <version>2.3.0</version>
 *  </dependency>
 *  <dependency>
 *      <groupId>com.alibaba</groupId>
 *      <artifactId>fastjson</artifactId>
 *      <version>1.2.9</version>
 *  </dependency>
 */
public class ScriptBatchEditingService {

    static final String regionId = "[your-region-id]"; // The feature is supported in cn-shanghai, cn-beijing, and cn-hangzhou.
    static final String bucket = "[your-bucket]";
    private Client iceClient;

    public static void main(String[] args) throws Exception {
        ScriptBatchEditingService scriptBatchEditingService = new ScriptBatchEditingService();
        scriptBatchEditingService.initClient();
        scriptBatchEditingService.runExample();
    }

    public void initClient() throws Exception {
        // An Alibaba Cloud account AccessKey has full access to all APIs. We recommend that you use a RAM user for API calls and routine O&M.
        // This example shows how to store the AccessKey ID and AccessKey secret in environment variables. For more information about how to configure them, see https://www.alibabacloud.com/help/en/sdk/developer-reference/v2-manage-access-credentials
        com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client();

        Config config = new Config();
        config.setCredential(credentialClient);

        // To hard-code the AccessKey ID and AccessKey secret, use the following code. However, we strongly recommend that you do not hard-code them in your project code. Otherwise, the AccessKey pair may be leaked, which compromises the security of all your resources.
        // config.accessKeyId = <The AccessKey ID created in Step 2>;
        // config.accessKeySecret = <The AccessKey secret created in Step 2>;
        config.endpoint = "ice." + regionId + ".aliyuncs.com";
        config.regionId = regionId;
        iceClient = new Client(config);
    }

    public void runExample() throws Exception {

        // Video materials
        JSONObject mediaGroup1 = new JSONObject();
        mediaGroup1.put("GroupName", "start");
        mediaGroup1.put("MediaArray", Arrays.asList(
            "http://ice-document-materials.oss-cn-shanghai.aliyuncs.com/test_media/lgh/lgh-start-1.mp4"
        ));

        JSONObject mediaGroup2 = new JSONObject();
        mediaGroup2.put("GroupName", "middle");
        mediaGroup2.put("MediaArray", Arrays.asList(
            "http://ice-document-materials.oss-cn-shanghai.aliyuncs.com/test_media/lgh/lgh-m-1.mp4",
            "http://ice-document-materials.oss-cn-shanghai.aliyuncs.com/test_media/lgh/lgh-m-2.mp4",
            "http://ice-document-materials.oss-cn-shanghai.aliyuncs.com/test_media/lgh/lgh-m-3.mp4"
        ));

        JSONObject mediaGroup3 = new JSONObject();
        mediaGroup3.put("GroupName", "end");
        mediaGroup3.put("MediaArray", Arrays.asList(
            "http://ice-document-materials.oss-cn-shanghai.aliyuncs.com/test_media/lgh/lgh-end-1.mp4"
        ));

        JSONArray mediaGroupArray = new JSONArray();
        mediaGroupArray.add(mediaGroup1);
        mediaGroupArray.add(mediaGroup2);
        mediaGroupArray.add(mediaGroup3);

        // Narration scripts
        List<String> speechTextArray = Arrays.asList(
            "Wondering where to go for the holiday? Lugu Lake in Yunnan invites you for a date with nature. The azure lake is like a mirror, reflecting the unique customs of the Mosuo Kingdom of Women, as picturesque as a painting.",
            "Still hesitant about your holiday plans? Why not consider a natural feast at Lugu Lake in Yunnan? The azure, mirror-like lake reflects the unique folk customs of the Mosuo Kingdom of Women, picturesque and fascinating."
        );

        // Video titles
        List<String> titleArray = Arrays.asList(
            "Lugu Lake: Mosuo customs in a beautiful landscape",
            "Exploring the mysterious Lugu Lake",
            "Immersive experience of Lugu Lake"
        );

        JSONObject inputConfig = new JSONObject();
        inputConfig.put("MediaGroupArray", mediaGroupArray);
        inputConfig.put("SpeechTextArray", speechTextArray);
        inputConfig.put("TitleArray", titleArray);

        // Number of videos to produce
        int produceCount = 4;

        // Output resolution (portrait)
        //int outputWidth = 1080;
        //int outputHeight = 1920;

        // Output resolution (landscape)
        int outputWidth = 1920;
        int outputHeight = 1080;

        // Output OSS URL, must include the {index} placeholder
        String mediaUrl = "http://" + bucket + ".oss-" + regionId + ".aliyuncs.com/script/output_{index}_w.mp4";

        JSONObject outputConfig = new JSONObject();
        outputConfig.put("MediaURL", mediaUrl);
        outputConfig.put("Count", produceCount);
        outputConfig.put("Width", outputWidth);
        outputConfig.put("Height", outputHeight);

        // Submit batch video production job
        SubmitBatchMediaProducingJobRequest request = new SubmitBatchMediaProducingJobRequest();
        request.setInputConfig(inputConfig.toJSONString());
        request.setOutputConfig(outputConfig.toJSONString());

        SubmitBatchMediaProducingJobResponse response = iceClient.submitBatchMediaProducingJob(request);
        String jobId = response.getBody().getJobId();
        System.out.println("Start script batch job, batchJobId: " + jobId);

        // Poll job status until all are finished
        System.out.println("Waiting job finished...");
        int maxTry = 3000;
        int i = 0;
        while (i < maxTry) {
            Thread.sleep(3000);
            i++;
            GetBatchMediaProducingJobRequest getRequest = new GetBatchMediaProducingJobRequest();
            getRequest.setJobId(jobId);
            GetBatchMediaProducingJobResponse getResponse = iceClient.getBatchMediaProducingJob(getRequest);
            String status = getResponse.getBody().getEditingBatchJob().getStatus();
            System.out.println("BatchJobId: " + jobId + ", status:" + status);

            if ("Failed".equals(status)) {
                System.out.println("Batch job failed. JobInfo: " + JSONObject.toJSONString(getResponse.getBody().getEditingBatchJob()));
                throw new Exception("Produce failed. BatchJobId: " + jobId);
            }

            if ("Finished".equals(status)) {
                System.out.println("Batch job finished. JobInfo: " + JSONObject.toJSONString(getResponse.getBody().getEditingBatchJob()));
                break;
            }
        }
    }
}

Parâmetros de entrada da API

InputConfig

{
  "MediaGroupArray": [{
    "GroupName": "start",
    "MediaArray": [
      "http://ice-document-materials.oss-cn-shanghai.aliyuncs.com/test_media/lgh/lgh-start-1.mp4"
    ]
  },
    {
      "GroupName": "middle",
      "MediaArray": [
        "http://ice-document-materials.oss-cn-shanghai.aliyuncs.com/test_media/lgh/lgh-m-1.mp4",
        "http://ice-document-materials.oss-cn-shanghai.aliyuncs.com/test_media/lgh/lgh-m-2.mp4",
        "http://ice-document-materials.oss-cn-shanghai.aliyuncs.com/test_media/lgh/lgh-m-3.mp4"
      ]
    },
    {
      "GroupName": "end",
      "MediaArray": [
        "http://ice-document-materials.oss-cn-shanghai.aliyuncs.com/test_media/lgh/lgh-end-1.mp4"
      ]
    }
  ],
  "SpeechTextArray": [
    "Wondering where to go for the holiday? Lugu Lake in Yunnan invites you for a date with nature. The azure lake is like a mirror, reflecting the unique customs of the Mosuo Kingdom of Women, as picturesque as a painting.",
    "Still hesitant about your holiday plans? Why not consider a natural feast at Lugu Lake in Yunnan? The azure, mirror-like lake reflects the unique folk customs of the Mosuo Kingdom of Women, picturesque and fascinating."
  ],
  "TitleArray": [
    "Lugu Lake: Mosuo customs in a beautiful landscape",
    "Exploring the mysterious Lugu Lake",
    "Immersive experience of Lugu Lake"
  ]
}

OutputConfig

{
  "Count": 4,
  "Height": 1080,
  "Width": 1920,
  "MediaURL": "http://[your-bucket].oss-<region-id>.aliyuncs.com/[your-file-path]/[your-file-name]
_{index}_w.mp4"
}

Configurações avançadas

Para configurações avançadas, consulte Lógica e configurações avançadas para criação de vídeo em lote com um clique.

FAQ

Para perguntas frequentes sobre Script-to-Video, consulte FAQ.

Referências