创建和管理作业模板

本页面介绍了如何创建和管理 Transcoder API 作业模板。

默认情况下,Transcoder API 会应用名为 preset/web-hd 的预设模板来填充作业配置。您可以在创建转码作业时指定自己的自定义作业模板。作业配置表示您在创建作业时可以自定义的许多设置。

设置您的 GCP 项目和身份验证

创建作业模板

您可以在作业模板中指定各种设置。如需了解作业配置的一些术语和概念,请参阅 Transcoder API 概览

如需创建作业模板,请使用 projects.locations.jobTemplates.create 方法。以下示例使用简单配置来创建标清和高清 .mp4 输出文件。如需详细了解作业配置,请参阅 JobConfig 参考文档。

REST 和命令行

在使用下面的请求数据之前,请先进行以下替换:

  • PROJECT_IDIAM 设置中列出的 Google Cloud 项目 ID。
  • LOCATION:作业模板的存储位置。请使用以下列表中的某个位置:
    • us-central1
    • us-west1
    • us-east1
    • southamerica-east1
    • asia-east1
    • europe-west1
  • TEMPLATE_ID:要创建的新作业模板的用户定义标识符。此值应为 4-63 个字符,有效字符在正则表达式 [a-zA-Z][a-zA-Z0-9_-]* 中。

请求 JSON 正文:

{
  "config": {
    "elementaryStreams": [
      {
        "key": "video-stream0",
        "videoStream": {
          "codec": "h264",
          "heightPixels": 360,
          "widthPixels": 640,
          "bitrateBps": 550000,
          "frameRate": 60
        }
      },
      {
        "key": "video-stream1",
        "videoStream": {
          "codec": "h264",
          "heightPixels": 720,
          "widthPixels": 1280,
          "bitrateBps": 2500000,
          "frameRate": 60
        }
      },
      {
        "key": "audio-stream0",
        "audioStream": {
          "codec": "aac",
          "bitrateBps": 64000
        }
      }
    ],
    "muxStreams": [
      {
        "key": "sd",
        "container": "mp4",
        "elementaryStreams": [
          "video-stream0",
          "audio-stream0"
        ]
      },
      {
        "key": "hd",
        "container": "mp4",
        "elementaryStreams": [
          "video-stream1",
          "audio-stream0"
        ]
      }
    ]
  }
}

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/jobTemplates/TEMPLATE_ID",
  "config": {
    "inputs": [
      {
        "key": "input0"
      }
    ],
    "editList": [
      {
        "key": "atom0",
        "inputs": [
          "input0"
        ],
        "startTimeOffset": "0s"
      }
    ],
    "elementaryStreams": [
      {
        "videoStream": {
          "codec": "h264",
          "profile": "high",
          "preset": "veryfast",
          "heightPixels": 360,
          "widthPixels": 640,
          "pixelFormat": "yuv420p",
          "bitrateBps": 550000,
          "rateControlMode": "vbr",
          "crfLevel": 21,
          "vbvSizeBits": 550000,
          "vbvFullnessBits": 495000,
          "gopDuration": "3s",
          "entropyCoder": "cabac",
          "frameRate": 60
        },
        "key": "video-stream0"
      },
      {
        "videoStream": {
          "codec": "h264",
          "profile": "high",
          "preset": "veryfast",
          "heightPixels": 720,
          "widthPixels": 1280,
          "pixelFormat": "yuv420p",
          "bitrateBps": 2500000,
          "rateControlMode": "vbr",
          "crfLevel": 21,
          "vbvSizeBits": 2500000,
          "vbvFullnessBits": 2250000,
          "gopDuration": "3s",
          "entropyCoder": "cabac",
          "frameRate": 60
        },
        "key": "video-stream1"
      },
      {
        "audioStream": {
          "codec": "aac",
          "bitrateBps": 64000,
          "channelCount": 2,
          "channelLayout": [
            "fl",
            "fr"
          ],
          "sampleRateHertz": 48000
        },
        "key": "audio-stream0"
      }
    ],
    "muxStreams": [
      {
        "key": "sd",
        "fileName": "sd.mp4",
        "container": "mp4",
        "elementaryStreams": [
          "video-stream0",
          "audio-stream0"
        ]
      },
      {
        "key": "hd",
        "fileName": "hd.mp4",
        "container": "mp4",
        "elementaryStreams": [
          "video-stream1",
          "audio-stream0"
        ]
      }
    ],
    "output": {}
  }
}

gcloud

  1. 创建一个定义作业模板字段的 config.json 文件。以下是示例作业模板:
    {
      "config": {
        "elementaryStreams": [
          {
            "key": "video-stream0",
            "videoStream": {
              "codec": "h264",
              "heightPixels": 360,
              "widthPixels": 640,
              "bitrateBps": 550000,
              "frameRate": 60
            }
          },
          {
            "key": "video-stream1",
            "videoStream": {
              "codec": "h264",
              "heightPixels": 720,
              "widthPixels": 1280,
              "bitrateBps": 2500000,
              "frameRate": 60
            }
          },
          {
            "key": "audio-stream0",
            "audioStream": {
              "codec": "aac",
              "bitrateBps": 64000
            }
          }
        ],
        "muxStreams": [
          {
            "key": "sd",
            "container": "mp4",
            "elementaryStreams": [
              "video-stream0",
              "audio-stream0"
            ]
          },
          {
            "key": "hd",
            "container": "mp4",
            "elementaryStreams": [
              "video-stream1",
              "audio-stream0"
            ]
          }
        ]
      }
    }
    
  2. gcloud 命令进行以下替换:
    • TEMPLATE_ID:要创建的新作业模板的用户定义标识符。此值应为 4-63 个字符,有效字符在正则表达式 [a-zA-Z][a-zA-Z0-9_-]* 中。
    • LOCATION:作业模板的存储位置。请使用以下列表中的某个位置:
      • us-central1
      • us-west1
      • us-east1
      • southamerica-east1
      • asia-east1
      • europe-west1
  3. 运行以下命令:
    gcloud beta transcoder templates create TEMPLATE_ID --file="config.json" --location=LOCATION
    您应该会看到如下所示的响应:
    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/jobTemplates/TEMPLATE_ID",
      "config": {
        "inputs": [
          {
            "key": "input0"
          }
        ],
        "editList": [
          {
            "key": "atom0",
            "inputs": [
              "input0"
            ],
            "startTimeOffset": "0s"
          }
        ],
        "elementaryStreams": [
          {
            "videoStream": {
              "codec": "h264",
              "profile": "high",
              "preset": "veryfast",
              "heightPixels": 360,
              "widthPixels": 640,
              "pixelFormat": "yuv420p",
              "bitrateBps": 550000,
              "rateControlMode": "vbr",
              "crfLevel": 21,
              "vbvSizeBits": 550000,
              "vbvFullnessBits": 495000,
              "gopDuration": "3s",
              "entropyCoder": "cabac",
              "frameRate": 60
            },
            "key": "video-stream0"
          },
          {
            "videoStream": {
              "codec": "h264",
              "profile": "high",
              "preset": "veryfast",
              "heightPixels": 720,
              "widthPixels": 1280,
              "pixelFormat": "yuv420p",
              "bitrateBps": 2500000,
              "rateControlMode": "vbr",
              "crfLevel": 21,
              "vbvSizeBits": 2500000,
              "vbvFullnessBits": 2250000,
              "gopDuration": "3s",
              "entropyCoder": "cabac",
              "frameRate": 60
            },
            "key": "video-stream1"
          },
          {
            "audioStream": {
              "codec": "aac",
              "bitrateBps": 64000,
              "channelCount": 2,
              "channelLayout": [
                "fl",
                "fr"
              ],
              "sampleRateHertz": 48000
            },
            "key": "audio-stream0"
          }
        ],
        "muxStreams": [
          {
            "key": "sd",
            "fileName": "sd.mp4",
            "container": "mp4",
            "elementaryStreams": [
              "video-stream0",
              "audio-stream0"
            ]
          },
          {
            "key": "hd",
            "fileName": "hd.mp4",
            "container": "mp4",
            "elementaryStreams": [
              "video-stream1",
              "audio-stream0"
            ]
          }
        ],
        "output": {}
      }
    }
    

Go

在试用此示例之前,请按照《Transcoder API 快速入门:使用客户端库》中的 Go 设置说明进行操作。如需了解详情,请参阅 Transcoder API Go API 参考文档

import (
	"context"
	"fmt"
	"io"

	transcoder "cloud.google.com/go/video/transcoder/apiv1beta1"
	transcoderpb "google.golang.org/genproto/googleapis/cloud/video/transcoder/v1beta1"
)

// createJobTemplate creates a template for a job. See
// https://cloud.google.com/transcoder/docs/how-to/job-templates#create_job_templates
// for more information.
func createJobTemplate(w io.Writer, projectID string, location string, templateID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// templateID := "my-job-template"
	ctx := context.Background()
	client, err := transcoder.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %v", err)
	}
	defer client.Close()

	req := &transcoderpb.CreateJobTemplateRequest{
		Parent:        fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		JobTemplateId: templateID,
		JobTemplate: &transcoderpb.JobTemplate{
			Config: &transcoderpb.JobConfig{
				ElementaryStreams: []*transcoderpb.ElementaryStream{
					&transcoderpb.ElementaryStream{
						Key: "video_stream0",
						ElementaryStream: &transcoderpb.ElementaryStream_VideoStream{
							VideoStream: &transcoderpb.VideoStream{
								Codec:        "h264",
								BitrateBps:   550000,
								FrameRate:    60,
								HeightPixels: 360,
								WidthPixels:  640,
							},
						},
					},
					&transcoderpb.ElementaryStream{
						Key: "video_stream1",
						ElementaryStream: &transcoderpb.ElementaryStream_VideoStream{
							VideoStream: &transcoderpb.VideoStream{
								Codec:        "h264",
								BitrateBps:   2500000,
								FrameRate:    60,
								HeightPixels: 720,
								WidthPixels:  1280,
							},
						},
					},
					&transcoderpb.ElementaryStream{
						Key: "audio_stream0",
						ElementaryStream: &transcoderpb.ElementaryStream_AudioStream{
							AudioStream: &transcoderpb.AudioStream{
								Codec:      "aac",
								BitrateBps: 64000,
							},
						},
					},
				},
				MuxStreams: []*transcoderpb.MuxStream{
					&transcoderpb.MuxStream{
						Key:               "sd",
						Container:         "mp4",
						ElementaryStreams: []string{"video_stream0", "audio_stream0"},
					},
					&transcoderpb.MuxStream{
						Key:               "hd",
						Container:         "mp4",
						ElementaryStreams: []string{"video_stream1", "audio_stream0"},
					},
				},
			},
		},
	}

	response, err := client.CreateJobTemplate(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateJobTemplate: %v", err)
	}

	fmt.Fprintf(w, "Job template: %v", response.GetName())
	return nil
}

Java

在试用此示例之前,请按照《Transcoder API 快速入门:使用客户端库》中的 Java 设置说明进行操作。如需了解详情,请参阅 Transcoder API Java API 参考文档


import com.google.cloud.video.transcoder.v1beta1.AudioStream;
import com.google.cloud.video.transcoder.v1beta1.CreateJobTemplateRequest;
import com.google.cloud.video.transcoder.v1beta1.ElementaryStream;
import com.google.cloud.video.transcoder.v1beta1.JobConfig;
import com.google.cloud.video.transcoder.v1beta1.JobTemplate;
import com.google.cloud.video.transcoder.v1beta1.LocationName;
import com.google.cloud.video.transcoder.v1beta1.MuxStream;
import com.google.cloud.video.transcoder.v1beta1.TranscoderServiceClient;
import com.google.cloud.video.transcoder.v1beta1.VideoStream;
import java.io.IOException;

public class CreateJobTemplate {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String location = "us-central1";
    String templateId = "my-job-template";

    createJobTemplate(projectId, location, templateId);
  }

  // Creates a job template.
  public static void createJobTemplate(String projectId, String location, String templateId)
      throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (TranscoderServiceClient transcoderServiceClient = TranscoderServiceClient.create()) {

      VideoStream videoStream0 =
          VideoStream.newBuilder()
              .setCodec("h264")
              .setBitrateBps(550000)
              .setFrameRate(60)
              .setHeightPixels(360)
              .setWidthPixels(640)
              .build();
      VideoStream videoStream1 =
          VideoStream.newBuilder()
              .setCodec("h264")
              .setBitrateBps(2500000)
              .setFrameRate(60)
              .setHeightPixels(720)
              .setWidthPixels(1280)
              .build();
      AudioStream audioStream0 =
          AudioStream.newBuilder().setCodec("aac").setBitrateBps(64000).build();
      JobConfig config =
          JobConfig.newBuilder()
              .addElementaryStreams(
                  ElementaryStream.newBuilder()
                      .setKey("video_stream0")
                      .setVideoStream(videoStream0))
              .addElementaryStreams(
                  ElementaryStream.newBuilder()
                      .setKey("video_stream1")
                      .setVideoStream(videoStream1))
              .addElementaryStreams(
                  ElementaryStream.newBuilder()
                      .setKey("audio_stream0")
                      .setAudioStream(audioStream0))
              .addMuxStreams(
                  MuxStream.newBuilder()
                      .setKey("sd")
                      .setContainer("mp4")
                      .addElementaryStreams("video_stream0")
                      .addElementaryStreams("audio_stream0")
                      .build())
              .addMuxStreams(
                  MuxStream.newBuilder()
                      .setKey("hd")
                      .setContainer("mp4")
                      .addElementaryStreams("video_stream1")
                      .addElementaryStreams("audio_stream0")
                      .build())
              .build();

      var createJobTemplateRequest =
          CreateJobTemplateRequest.newBuilder()
              .setParent(LocationName.of(projectId, location).toString())
              .setJobTemplateId(templateId)
              .setJobTemplate(JobTemplate.newBuilder().setConfig(config).build())
              .build();

      // Send the job template creation request and process the response.
      JobTemplate jobTemplate = transcoderServiceClient.createJobTemplate(createJobTemplateRequest);
      System.out.println("Job template: " + jobTemplate.getName());
    }
  }
}

Node.js

在尝试此示例之前,请按照《Transcoder API 快速入门:使用客户端库》中的 Node.js 设置说明进行操作。如需了解详情,请参阅 Transcoder API Node.js API 参考文档

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project-id';
// location = 'us-central1';
// templateId = 'my-job-template';

// Imports the Transcoder library
const {TranscoderServiceClient} = require('@google-cloud/video-transcoder');

// Instantiates a client
const transcoderServiceClient = new TranscoderServiceClient();

async function createJobTemplate() {
  // Construct request
  const request = {
    parent: transcoderServiceClient.locationPath(projectId, location),
    jobTemplateId: templateId,
    jobTemplate: {
      config: {
        elementaryStreams: [
          {
            key: 'video-stream0',
            videoStream: {
              codec: 'h264',
              heightPixels: 360,
              widthPixels: 640,
              bitrateBps: 550000,
              frameRate: 60,
            },
          },
          {
            key: 'video-stream1',
            videoStream: {
              codec: 'h264',
              heightPixels: 720,
              widthPixels: 1280,
              bitrateBps: 2500000,
              frameRate: 60,
            },
          },
          {
            key: 'audio-stream0',
            audioStream: {
              codec: 'aac',
              bitrateBps: 64000,
            },
          },
        ],
        muxStreams: [
          {
            key: 'sd',
            container: 'mp4',
            elementaryStreams: ['video-stream0', 'audio-stream0'],
          },
          {
            key: 'hd',
            container: 'mp4',
            elementaryStreams: ['video-stream1', 'audio-stream0'],
          },
        ],
      },
    },
  };

  // Run request
  const [jobTemplate] = await transcoderServiceClient.createJobTemplate(
    request
  );
  console.log(`Job template: ${jobTemplate.name}`);
}

createJobTemplate();

Python

在试用此示例之前,请按照《Transcoder API 快速入门:使用客户端库》中的 Python 设置说明进行操作。如需了解详情,请参阅 Transcoder API Python API 参考文档


import argparse

from google.cloud.video import transcoder_v1beta1
from google.cloud.video.transcoder_v1beta1.services.transcoder_service import (
    TranscoderServiceClient,
)

def create_job_template(project_id, location, template_id):
    """Creates a job template.

    Args:
        project_id: The GCP project ID.
        location: The location to store this template in.
        template_id: The user-defined template ID."""

    client = TranscoderServiceClient()

    parent = f"projects/{project_id}/locations/{location}"

    job_template = transcoder_v1beta1.types.JobTemplate()
    job_template.name = (
        f"projects/{project_id}/locations/{location}/jobTemplates/{template_id}"
    )
    job_template.config = transcoder_v1beta1.types.JobConfig(
        elementary_streams=[
            transcoder_v1beta1.types.ElementaryStream(
                key="video-stream0",
                video_stream=transcoder_v1beta1.types.VideoStream(
                    codec="h264",
                    height_pixels=360,
                    width_pixels=640,
                    bitrate_bps=550000,
                    frame_rate=60,
                ),
            ),
            transcoder_v1beta1.types.ElementaryStream(
                key="video-stream1",
                video_stream=transcoder_v1beta1.types.VideoStream(
                    codec="h264",
                    height_pixels=720,
                    width_pixels=1280,
                    bitrate_bps=2500000,
                    frame_rate=60,
                ),
            ),
            transcoder_v1beta1.types.ElementaryStream(
                key="audio-stream0",
                audio_stream=transcoder_v1beta1.types.AudioStream(
                    codec="aac", bitrate_bps=64000
                ),
            ),
        ],
        mux_streams=[
            transcoder_v1beta1.types.MuxStream(
                key="sd",
                container="mp4",
                elementary_streams=["video-stream0", "audio-stream0"],
            ),
            transcoder_v1beta1.types.MuxStream(
                key="hd",
                container="mp4",
                elementary_streams=["video-stream1", "audio-stream0"],
            ),
        ],
    )

    response = client.create_job_template(
        parent=parent, job_template=job_template, job_template_id=template_id
    )
    print(f"Job template: {response.name}")
    return response

获取作业模板详情

如需详细了解作业模板,请使用 projects.locations.jobTemplates.get 方法。

REST 和命令行

在使用下面的请求数据之前,请先进行以下替换:

  • TEMPLATE_ID:您创建的作业模板的 ID。
  • PROJECT_ID:您的 Google Cloud 项目 ID。
  • LOCATION:您的作业模板的位置。请使用以下列表中的某个位置:
    • us-central1
    • us-west1
    • us-east1
    • southamerica-east1
    • asia-east1
    • europe-west1
  • 根据您发送的请求,请展开以下选项之一:

    您应该收到类似以下内容的 JSON 响应:

    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/jobTemplates/TEMPLATE_ID",
      "config": {
        "inputs": [
          {
            "key": "input0"
          }
        ],
        "editList": [
          {
            "key": "atom0",
            "inputs": [
              "input0"
            ],
            "startTimeOffset": "0s"
          }
        ],
        "elementaryStreams": [
          {
            "videoStream": {
              "codec": "h264",
              "profile": "high",
              "preset": "veryfast",
              "heightPixels": 360,
              "widthPixels": 640,
              "pixelFormat": "yuv420p",
              "bitrateBps": 550000,
              "rateControlMode": "vbr",
              "crfLevel": 21,
              "vbvSizeBits": 550000,
              "vbvFullnessBits": 495000,
              "gopDuration": "3s",
              "entropyCoder": "cabac",
              "frameRate": 60
            },
            "key": "video-stream0"
          },
          {
            "videoStream": {
              "codec": "h264",
              "profile": "high",
              "preset": "veryfast",
              "heightPixels": 720,
              "widthPixels": 1280,
              "pixelFormat": "yuv420p",
              "bitrateBps": 2500000,
              "rateControlMode": "vbr",
              "crfLevel": 21,
              "vbvSizeBits": 2500000,
              "vbvFullnessBits": 2250000,
              "gopDuration": "3s",
              "entropyCoder": "cabac",
              "frameRate": 60
            },
            "key": "video-stream1"
          },
          {
            "audioStream": {
              "codec": "aac",
              "bitrateBps": 64000,
              "channelCount": 2,
              "channelLayout": [
                "fl",
                "fr"
              ],
              "sampleRateHertz": 48000
            },
            "key": "audio-stream0"
          }
        ],
        "muxStreams": [
          {
            "key": "sd",
            "fileName": "sd.mp4",
            "container": "mp4",
            "elementaryStreams": [
              "video-stream0",
              "audio-stream0"
            ]
          },
          {
            "key": "hd",
            "fileName": "hd.mp4",
            "container": "mp4",
            "elementaryStreams": [
              "video-stream1",
              "audio-stream0"
            ]
          }
        ],
        "output": {}
      }
    }
    

    gcloud

    1. gcloud 命令进行以下替换:
      • TEMPLATE_ID:您创建的作业模板的 ID。
      • LOCATION:您的作业模板的位置。请使用以下列表中的某个位置:
        • us-central1
        • us-west1
        • us-east1
        • southamerica-east1
        • asia-east1
        • europe-west1
    2. 运行以下命令:
      gcloud beta transcoder templates describe TEMPLATE_ID --location=LOCATION
      您应该会看到如下所示的响应:
      {
        "name": "projects/PROJECT_NUMBER/locations/LOCATION/jobTemplates/TEMPLATE_ID",
        "config": {
          "inputs": [
            {
              "key": "input0"
            }
          ],
          "editList": [
            {
              "key": "atom0",
              "inputs": [
                "input0"
              ],
              "startTimeOffset": "0s"
            }
          ],
          "elementaryStreams": [
            {
              "videoStream": {
                "codec": "h264",
                "profile": "high",
                "preset": "veryfast",
                "heightPixels": 360,
                "widthPixels": 640,
                "pixelFormat": "yuv420p",
                "bitrateBps": 550000,
                "rateControlMode": "vbr",
                "crfLevel": 21,
                "vbvSizeBits": 550000,
                "vbvFullnessBits": 495000,
                "gopDuration": "3s",
                "entropyCoder": "cabac",
                "frameRate": 60
              },
              "key": "video-stream0"
            },
            {
              "videoStream": {
                "codec": "h264",
                "profile": "high",
                "preset": "veryfast",
                "heightPixels": 720,
                "widthPixels": 1280,
                "pixelFormat": "yuv420p",
                "bitrateBps": 2500000,
                "rateControlMode": "vbr",
                "crfLevel": 21,
                "vbvSizeBits": 2500000,
                "vbvFullnessBits": 2250000,
                "gopDuration": "3s",
                "entropyCoder": "cabac",
                "frameRate": 60
              },
              "key": "video-stream1"
            },
            {
              "audioStream": {
                "codec": "aac",
                "bitrateBps": 64000,
                "channelCount": 2,
                "channelLayout": [
                  "fl",
                  "fr"
                ],
                "sampleRateHertz": 48000
              },
              "key": "audio-stream0"
            }
          ],
          "muxStreams": [
            {
              "key": "sd",
              "fileName": "sd.mp4",
              "container": "mp4",
              "elementaryStreams": [
                "video-stream0",
                "audio-stream0"
              ]
            },
            {
              "key": "hd",
              "fileName": "hd.mp4",
              "container": "mp4",
              "elementaryStreams": [
                "video-stream1",
                "audio-stream0"
              ]
            }
          ],
          "output": {}
        }
      }
      

    Go

    在试用此示例之前,请按照《Transcoder API 快速入门:使用客户端库》中的 Go 设置说明进行操作。如需了解详情,请参阅 Transcoder API Go API 参考文档

    import (
    	"context"
    	"fmt"
    	"io"
    
    	transcoder "cloud.google.com/go/video/transcoder/apiv1beta1"
    	transcoderpb "google.golang.org/genproto/googleapis/cloud/video/transcoder/v1beta1"
    )
    
    // getJobTemplate gets a previously-created job template. See
    // https://cloud.google.com/transcoder/docs/how-to/job-templates#get_job_template
    // for more information.
    func getJobTemplate(w io.Writer, projectID string, location string, templateID string) error {
    	// projectID := "my-project-id"
    	// location := "us-central1"
    	// templateID := "my-job-template"
    	ctx := context.Background()
    	client, err := transcoder.NewClient(ctx)
    	if err != nil {
    		return fmt.Errorf("NewClient: %v", err)
    	}
    	defer client.Close()
    
    	req := &transcoderpb.GetJobTemplateRequest{
    		Name: fmt.Sprintf("projects/%s/locations/%s/jobTemplates/%s", projectID, location, templateID),
    	}
    
    	response, err := client.GetJobTemplate(ctx, req)
    	if err != nil {
    		return fmt.Errorf("GetJobTemplate: %v", err)
    	}
    
    	fmt.Fprintf(w, "Job template: %v", response.GetName())
    	return nil
    }
    

    Java

    在试用此示例之前,请按照《Transcoder API 快速入门:使用客户端库》中的 Java 设置说明进行操作。如需了解详情,请参阅 Transcoder API Java API 参考文档

    
    import com.google.cloud.video.transcoder.v1beta1.GetJobTemplateRequest;
    import com.google.cloud.video.transcoder.v1beta1.JobTemplate;
    import com.google.cloud.video.transcoder.v1beta1.JobTemplateName;
    import com.google.cloud.video.transcoder.v1beta1.TranscoderServiceClient;
    import java.io.IOException;
    
    public class GetJobTemplate {
    
      public static void main(String[] args) throws Exception {
        // TODO(developer): Replace these variables before running the sample.
        String projectId = "my-project-id";
        String location = "us-central1";
        String templateId = "my-job-template";
    
        getJobTemplate(projectId, location, templateId);
      }
    
      // Gets a job template.
      public static void getJobTemplate(String projectId, String location, String templateId)
          throws IOException {
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests.
        try (TranscoderServiceClient transcoderServiceClient = TranscoderServiceClient.create()) {
          JobTemplateName jobTemplateName =
              JobTemplateName.newBuilder()
                  .setProject(projectId)
                  .setLocation(location)
                  .setJobTemplate(templateId)
                  .build();
          var getJobTemplateRequest =
              GetJobTemplateRequest.newBuilder().setName(jobTemplateName.toString()).build();
    
          // Send the get job template request and process the response.
          JobTemplate jobTemplate = transcoderServiceClient.getJobTemplate(getJobTemplateRequest);
          System.out.println("Job template: " + jobTemplate.getName());
        }
      }
    }

    Node.js

    在尝试此示例之前,请按照《Transcoder API 快速入门:使用客户端库》中的 Node.js 设置说明进行操作。如需了解详情,请参阅 Transcoder API Node.js API 参考文档

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // projectId = 'my-project-id';
    // location = 'us-central1';
    // templateId = 'my-job-template';
    
    // Imports the Transcoder library
    const {TranscoderServiceClient} = require('@google-cloud/video-transcoder');
    
    // Instantiates a client
    const transcoderServiceClient = new TranscoderServiceClient();
    
    async function getJobTemplate() {
      // Construct request
      const request = {
        name: transcoderServiceClient.jobTemplatePath(
          projectId,
          location,
          templateId
        ),
      };
      const [jobTemplate] = await transcoderServiceClient.getJobTemplate(request);
      console.log(`Job template: ${jobTemplate.name}`);
    }
    
    getJobTemplate();

    Python

    在试用此示例之前,请按照《Transcoder API 快速入门:使用客户端库》中的 Python 设置说明进行操作。如需了解详情,请参阅 Transcoder API Python API 参考文档

    
    import argparse
    
    from google.cloud.video.transcoder_v1beta1.services.transcoder_service import (
        TranscoderServiceClient,
    )
    
    def get_job_template(project_id, location, template_id):
        """Gets a job template.
    
        Args:
            project_id: The GCP project ID.
            location: The location of the template.
            template_id: The user-defined template ID."""
    
        client = TranscoderServiceClient()
    
        name = f"projects/{project_id}/locations/{location}/jobTemplates/{template_id}"
        response = client.get_job_template(name=name)
        print(f"Job template: {response.name}")
        return response
    
    

    列出作业模板

    如果要查看在某个位置创建的所有作业模板,请使用 projects.locations.jobTemplates.list 方法。

    REST 和命令行

    在使用下面的请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的 Google Cloud 项目 ID。
  • LOCATION:您的作业模板的位置。请使用以下列表中的某个位置:
    • us-central1
    • us-west1
    • us-east1
    • southamerica-east1
    • asia-east1
    • europe-west1
  • 根据您发送的请求,请展开以下选项之一:

    您应该收到类似以下内容的 JSON 响应:

    {
      "jobTemplates": [
        {
          "name": "projects/PROJECT_NUMBER/locations/LOCATION/jobTemplates/TEMPLATE_ID",
          "config": {
             ...
          }
        },
        {
          "name": "projects/PROJECT_NUMBER/locations/LOCATION/jobTemplates/my-other-template",
          "config": {
             ...
          }
        }
      ]
    }
    

    gcloud

    1. gcloud 命令进行以下替换:
      • LOCATION:您的作业模板的位置。请使用以下列表中的某个位置:
        • us-central1
        • us-west1
        • us-east1
        • southamerica-east1
        • asia-east1
        • europe-west1
    2. 运行以下命令:
      gcloud beta transcoder templates list --location=LOCATION
      您应该会看到如下所示的响应:
      NAME
      projects/PROJECT_NUMBER/locations/LOCATION/jobTemplates/TEMPLATE_ID
      projects/PROJECT_NUMBER/locations/LOCATION/jobTemplates/my-other-template
      

    Go

    在试用此示例之前,请按照《Transcoder API 快速入门:使用客户端库》中的 Go 设置说明进行操作。如需了解详情,请参阅 Transcoder API Go API 参考文档

    import (
    	"context"
    	"fmt"
    	"io"
    
    	"google.golang.org/api/iterator"
    
    	transcoder "cloud.google.com/go/video/transcoder/apiv1beta1"
    	transcoderpb "google.golang.org/genproto/googleapis/cloud/video/transcoder/v1beta1"
    )
    
    // listJobTemplates gets all previously-created job templates for a given
    // location. See
    // https://cloud.google.com/transcoder/docs/how-to/job-templates#list_job_template
    // for more information.
    func listJobTemplates(w io.Writer, projectID string, location string) error {
    	// projectID := "my-project-id"
    	// location := "us-central1"
    	ctx := context.Background()
    	client, err := transcoder.NewClient(ctx)
    	if err != nil {
    		return fmt.Errorf("NewClient: %v", err)
    	}
    	defer client.Close()
    
    	req := &transcoderpb.ListJobTemplatesRequest{
    		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
    	}
    
    	it := client.ListJobTemplates(ctx, req)
    	fmt.Fprintln(w, "Job templates:")
    	for {
    		response, err := it.Next()
    		if err == iterator.Done {
    			break
    		}
    		if err != nil {
    			return fmt.Errorf("ListJobTemplates: %v", err)
    		}
    		fmt.Fprintln(w, response.GetName())
    	}
    
    	return nil
    }
    

    Java

    在试用此示例之前,请按照《Transcoder API 快速入门:使用客户端库》中的 Java 设置说明进行操作。如需了解详情,请参阅 Transcoder API Java API 参考文档

    
    import com.google.cloud.video.transcoder.v1beta1.JobTemplate;
    import com.google.cloud.video.transcoder.v1beta1.ListJobTemplatesRequest;
    import com.google.cloud.video.transcoder.v1beta1.LocationName;
    import com.google.cloud.video.transcoder.v1beta1.TranscoderServiceClient;
    import java.io.IOException;
    
    public class ListJobTemplates {
    
      public static void main(String[] args) throws Exception {
        // TODO(developer): Replace these variables before running the sample.
        String projectId = "my-project-id";
        String location = "us-central1";
    
        listJobTemplates(projectId, location);
      }
    
      // Lists the job templates for a given location.
      public static void listJobTemplates(String projectId, String location) throws IOException {
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests.
        try (TranscoderServiceClient transcoderServiceClient = TranscoderServiceClient.create()) {
    
          var listJobTemplatesRequest =
              ListJobTemplatesRequest.newBuilder()
                  .setParent(LocationName.of(projectId, location).toString())
                  .build();
    
          // Send the list job templates request and process the response.
          TranscoderServiceClient.ListJobTemplatesPagedResponse response =
              transcoderServiceClient.listJobTemplates(listJobTemplatesRequest);
          System.out.println("Job templates:");
    
          for (JobTemplate jobTemplate : response.iterateAll()) {
            System.out.println(jobTemplate.getName());
          }
        }
      }
    }

    Node.js

    在尝试此示例之前,请按照《Transcoder API 快速入门:使用客户端库》中的 Node.js 设置说明进行操作。如需了解详情,请参阅 Transcoder API Node.js API 参考文档

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // projectId = 'my-project-id';
    // location = 'us-central1';
    
    // Imports the Transcoder library
    const {TranscoderServiceClient} = require('@google-cloud/video-transcoder');
    
    // Instantiates a client
    const transcoderServiceClient = new TranscoderServiceClient();
    
    async function listJobTemplates() {
      const [jobTemplates] = await transcoderServiceClient.listJobTemplates({
        parent: transcoderServiceClient.locationPath(projectId, location),
      });
      console.info('Job templates:');
      for (const jobTemplate of jobTemplates) {
        console.info(jobTemplate.name);
      }
    }
    
    listJobTemplates();

    Python

    在试用此示例之前,请按照《Transcoder API 快速入门:使用客户端库》中的 Python 设置说明进行操作。如需了解详情,请参阅 Transcoder API Python API 参考文档

    
    import argparse
    
    from google.cloud.video.transcoder_v1beta1.services.transcoder_service import (
        TranscoderServiceClient,
    )
    
    def list_job_templates(project_id, location):
        """Lists all job templates in a location.
    
        Args:
            project_id: The GCP project ID.
            location: The location of the templates."""
    
        client = TranscoderServiceClient()
    
        parent = f"projects/{project_id}/locations/{location}"
        response = client.list_job_templates(parent=parent)
        print("Job templates:")
        for jobTemplate in response.job_templates:
            print({jobTemplate.name})
    
        return response
    
    

    此响应可能包含 nextPageToken,可用于检索其他结果:

    {
      "jobTemplates": [
        ...
      ],
      "nextPageToken": "NEXT_PAGE_TOKEN"
    }
    

    在以下 curl 示例中,您可以发送另一个请求,并添加 NEXT_PAGE_TOKEN 的值以列出其他作业模板,类似以下内容:

    curl -X GET \
    -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
    https://transcoder.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/jobTemplates?pageToken=NEXT_PAGE_TOKEN
    

    如需详细了解如何使用此令牌,请参阅相关的客户端库

    删除作业模板

    如需删除作业模板,请使用 projects.locations.jobTemplates.delete 方法。

    REST 和命令行

    在使用下面的请求数据之前,请先进行以下替换:

  • TEMPLATE_ID:您创建的作业模板的 ID。
  • PROJECT_ID:您的 Google Cloud 项目 ID。
  • LOCATION:您的作业模板的位置。请使用以下列表中的某个位置:
    • us-central1
    • us-west1
    • us-east1
    • southamerica-east1
    • asia-east1
    • europe-west1
  • 根据您发送的请求,请展开以下选项之一:

    您应该收到类似以下内容的 JSON 响应:

    {}
    

    gcloud

    1. gcloud 命令进行以下替换:
      • TEMPLATE_ID:您创建的作业模板的 ID。
      • LOCATION:您的作业模板的位置。请使用以下列表中的某个位置:
        • us-central1
        • us-west1
        • us-east1
        • southamerica-east1
        • asia-east1
        • europe-west1
    2. 运行以下命令:
      gcloud beta transcoder templates delete TEMPLATE_ID --location=LOCATION
      您应该会看到如下所示的响应:
      Deleted template [projects/PROJECT_ID/locations/LOCATION/jobTemplates/TEMPLATE_ID].
      

    Go

    在试用此示例之前,请按照《Transcoder API 快速入门:使用客户端库》中的 Go 设置说明进行操作。如需了解详情,请参阅 Transcoder API Go API 参考文档

    import (
    	"context"
    	"fmt"
    	"io"
    
    	transcoder "cloud.google.com/go/video/transcoder/apiv1beta1"
    	transcoderpb "google.golang.org/genproto/googleapis/cloud/video/transcoder/v1beta1"
    )
    
    // deleteJobTemplate deletes a previously-created template for a job. See
    // https://cloud.google.com/transcoder/docs/how-to/job-templates#delete_job_template
    // for more information.
    func deleteJobTemplate(w io.Writer, projectID string, location string, templateID string) error {
    	// projectID := "my-project-id"
    	// location := "us-central1"
    	// templateID := "my-job-template"
    	ctx := context.Background()
    	client, err := transcoder.NewClient(ctx)
    	if err != nil {
    		return fmt.Errorf("NewClient: %v", err)
    	}
    	defer client.Close()
    
    	req := &transcoderpb.DeleteJobTemplateRequest{
    		Name: fmt.Sprintf("projects/%s/locations/%s/jobTemplates/%s", projectID, location, templateID),
    	}
    
    	err = client.DeleteJobTemplate(ctx, req)
    	if err != nil {
    		return fmt.Errorf("DeleteJobTemplate: %v", err)
    	}
    
    	fmt.Fprintf(w, "Deleted job template")
    	return nil
    }
    

    Java

    在试用此示例之前,请按照《Transcoder API 快速入门:使用客户端库》中的 Java 设置说明进行操作。如需了解详情,请参阅 Transcoder API Java API 参考文档

    
    import com.google.cloud.video.transcoder.v1beta1.DeleteJobTemplateRequest;
    import com.google.cloud.video.transcoder.v1beta1.JobTemplateName;
    import com.google.cloud.video.transcoder.v1beta1.TranscoderServiceClient;
    import java.io.IOException;
    
    public class DeleteJobTemplate {
    
      public static void main(String[] args) throws Exception {
        // TODO(developer): Replace these variables before running the sample.
        String projectId = "my-project-id";
        String location = "us-central1";
        String templateId = "my-job-template";
    
        deleteJobTemplate(projectId, location, templateId);
      }
    
      // Deletes a job template.
      public static void deleteJobTemplate(String projectId, String location, String templateId)
          throws IOException {
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests.
        try (TranscoderServiceClient transcoderServiceClient = TranscoderServiceClient.create()) {
          JobTemplateName jobTemplateName =
              JobTemplateName.newBuilder()
                  .setProject(projectId)
                  .setLocation(location)
                  .setJobTemplate(templateId)
                  .build();
          var deleteJobTemplateRequest =
              DeleteJobTemplateRequest.newBuilder().setName(jobTemplateName.toString()).build();
    
          // Send the delete job template request and process the response.
          transcoderServiceClient.deleteJobTemplate(deleteJobTemplateRequest);
          System.out.println("Deleted job template");
        }
      }
    }

    Node.js

    在尝试此示例之前,请按照《Transcoder API 快速入门:使用客户端库》中的 Node.js 设置说明进行操作。如需了解详情,请参阅 Transcoder API Node.js API 参考文档

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // projectId = 'my-project-id';
    // location = 'us-central1';
    // templateId = 'my-job-template';
    
    // Imports the Transcoder library
    const {TranscoderServiceClient} = require('@google-cloud/video-transcoder');
    
    // Instantiates a client
    const transcoderServiceClient = new TranscoderServiceClient();
    
    async function deleteJobTemplate() {
      // Construct request
      const request = {
        name: transcoderServiceClient.jobTemplatePath(
          projectId,
          location,
          templateId
        ),
      };
      await transcoderServiceClient.deleteJobTemplate(request);
      console.log('Deleted job template');
    }
    
    deleteJobTemplate();

    Python

    在试用此示例之前,请按照《Transcoder API 快速入门:使用客户端库》中的 Python 设置说明进行操作。如需了解详情,请参阅 Transcoder API Python API 参考文档

    
    import argparse
    
    from google.cloud.video.transcoder_v1beta1.services.transcoder_service import (
        TranscoderServiceClient,
    )
    
    def delete_job_template(project_id, location, template_id):
        """Deletes a job template.
    
        Args:
            project_id: The GCP project ID.
            location: The location of the template.
            template_id: The user-defined template ID."""
    
        client = TranscoderServiceClient()
    
        name = f"projects/{project_id}/locations/{location}/jobTemplates/{template_id}"
        response = client.delete_job_template(name=name)
        print("Deleted job template")
        return response
    
    

    后续步骤

    了解如何创建和管理作业