작업 템플릿 만들기

작업 구성을 정의하는 트랜스코딩 작업 템플릿을 만듭니다.

더 살펴보기

이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.

코드 샘플

C#

이 샘플을 사용해 보기 전에 Transcoder API 빠른 시작: 클라이언트 라이브러리 사용C# 설정 안내를 따르세요. 자세한 내용은 Transcoder API C# API 참조 문서를 확인하세요.

Transcoder API에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Video.Transcoder.V1;

public class CreateJobTemplateSample
{
    public JobTemplate CreateJobTemplate(
        string projectId, string location, string templateId)
    {
        // Create the client.
        TranscoderServiceClient client = TranscoderServiceClient.Create();

        // Build the parent location name.
        LocationName parentLocation = new LocationName(projectId, location);

        // Build the job template config.
        VideoStream videoStream0 = new VideoStream
        {
            H264 = new VideoStream.Types.H264CodecSettings
            {
                BitrateBps = 550000,
                FrameRate = 60,
                HeightPixels = 360,
                WidthPixels = 640
            }
        };

        VideoStream videoStream1 = new VideoStream
        {
            H264 = new VideoStream.Types.H264CodecSettings
            {
                BitrateBps = 2500000,
                FrameRate = 60,
                HeightPixels = 720,
                WidthPixels = 1280
            }
        };

        AudioStream audioStream0 = new AudioStream
        {
            Codec = "aac",
            BitrateBps = 64000
        };

        ElementaryStream elementaryStream0 = new ElementaryStream
        {
            Key = "video_stream0",
            VideoStream = videoStream0
        };

        ElementaryStream elementaryStream1 = new ElementaryStream
        {
            Key = "video_stream1",
            VideoStream = videoStream1
        };

        ElementaryStream elementaryStream2 = new ElementaryStream
        {
            Key = "audio_stream0",
            AudioStream = audioStream0
        };

        MuxStream muxStream0 = new MuxStream
        {
            Key = "sd",
            Container = "mp4",
            ElementaryStreams = { "video_stream0", "audio_stream0" }
        };

        MuxStream muxStream1 = new MuxStream
        {
            Key = "hd",
            Container = "mp4",
            ElementaryStreams = { "video_stream1", "audio_stream0" }
        };

        JobConfig jobConfig = new JobConfig
        {
            ElementaryStreams = { elementaryStream0, elementaryStream1, elementaryStream2 },
            MuxStreams = { muxStream0, muxStream1 }
        };

        JobTemplate newJobTemplate = new JobTemplate
        {
            Config = jobConfig
        };

        // Call the API.
        JobTemplate jobTemplate = client.CreateJobTemplate(parentLocation, newJobTemplate, templateId);
        return jobTemplate;
    }
}

Go

이 샘플을 사용해 보기 전에 Transcoder API 빠른 시작: 클라이언트 라이브러리 사용Go 설정 안내를 따르세요. 자세한 내용은 Transcoder API Go API 참조 문서를 확인하세요.

Transcoder API에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"

	transcoder "cloud.google.com/go/video/transcoder/apiv1"
	"cloud.google.com/go/video/transcoder/apiv1/transcoderpb"
)

// 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: %w", 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{
					{
						Key: "video_stream0",
						ElementaryStream: &transcoderpb.ElementaryStream_VideoStream{
							VideoStream: &transcoderpb.VideoStream{
								CodecSettings: &transcoderpb.VideoStream_H264{
									H264: &transcoderpb.VideoStream_H264CodecSettings{
										BitrateBps:   550000,
										FrameRate:    60,
										HeightPixels: 360,
										WidthPixels:  640,
									},
								},
							},
						},
					},
					{
						Key: "video_stream1",
						ElementaryStream: &transcoderpb.ElementaryStream_VideoStream{
							VideoStream: &transcoderpb.VideoStream{
								CodecSettings: &transcoderpb.VideoStream_H264{
									H264: &transcoderpb.VideoStream_H264CodecSettings{
										BitrateBps:   2500000,
										FrameRate:    60,
										HeightPixels: 720,
										WidthPixels:  1280,
									},
								},
							},
						},
					},
					{
						Key: "audio_stream0",
						ElementaryStream: &transcoderpb.ElementaryStream_AudioStream{
							AudioStream: &transcoderpb.AudioStream{
								Codec:      "aac",
								BitrateBps: 64000,
							},
						},
					},
				},
				MuxStreams: []*transcoderpb.MuxStream{
					{
						Key:               "sd",
						Container:         "mp4",
						ElementaryStreams: []string{"video_stream0", "audio_stream0"},
					},
					{
						Key:               "hd",
						Container:         "mp4",
						ElementaryStreams: []string{"video_stream1", "audio_stream0"},
					},
				},
			},
		},
	}

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

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

Java

이 샘플을 사용해 보기 전에 Transcoder API 빠른 시작: 클라이언트 라이브러리 사용Java 설정 안내를 따르세요. 자세한 내용은 Transcoder API Java API 참조 문서를 확인하세요.

Transcoder API에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import com.google.cloud.video.transcoder.v1.AudioStream;
import com.google.cloud.video.transcoder.v1.CreateJobTemplateRequest;
import com.google.cloud.video.transcoder.v1.ElementaryStream;
import com.google.cloud.video.transcoder.v1.JobConfig;
import com.google.cloud.video.transcoder.v1.JobTemplate;
import com.google.cloud.video.transcoder.v1.LocationName;
import com.google.cloud.video.transcoder.v1.MuxStream;
import com.google.cloud.video.transcoder.v1.TranscoderServiceClient;
import com.google.cloud.video.transcoder.v1.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()
              .setH264(
                  VideoStream.H264CodecSettings.newBuilder()
                      .setBitrateBps(550000)
                      .setFrameRate(60)
                      .setHeightPixels(360)
                      .setWidthPixels(640))
              .build();

      VideoStream videoStream1 =
          VideoStream.newBuilder()
              .setH264(
                  VideoStream.H264CodecSettings.newBuilder()
                      .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();

      CreateJobTemplateRequest 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 참조 문서를 확인하세요.

Transcoder 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').v1;

// 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: {
              h264: {
                heightPixels: 360,
                widthPixels: 640,
                bitrateBps: 550000,
                frameRate: 60,
              },
            },
          },
          {
            key: 'video-stream1',
            videoStream: {
              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();

PHP

이 샘플을 사용해 보기 전에 Transcoder API 빠른 시작: 클라이언트 라이브러리 사용PHP 설정 안내를 따르세요. 자세한 내용은 Transcoder API PHP API 참조 문서를 확인하세요.

Transcoder API에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

use Google\Cloud\Video\Transcoder\V1\AudioStream;
use Google\Cloud\Video\Transcoder\V1\Client\TranscoderServiceClient;
use Google\Cloud\Video\Transcoder\V1\CreateJobTemplateRequest;
use Google\Cloud\Video\Transcoder\V1\ElementaryStream;
use Google\Cloud\Video\Transcoder\V1\JobConfig;
use Google\Cloud\Video\Transcoder\V1\JobTemplate;
use Google\Cloud\Video\Transcoder\V1\MuxStream;
use Google\Cloud\Video\Transcoder\V1\VideoStream;

/**
 * Creates a job template.
 *
 * @param string $projectId The ID of your Google Cloud Platform project.
 * @param string $location The location of the job template.
 * @param string $templateId The user-defined template ID.
 */
function create_job_template($projectId, $location, $templateId)
{
    // Instantiate a client.
    $transcoderServiceClient = new TranscoderServiceClient();

    $formattedParent = $transcoderServiceClient->locationName($projectId, $location);

    $jobTemplate = (new JobTemplate())->setConfig(
        (new JobConfig())->setElementaryStreams([
            (new ElementaryStream())
                ->setKey('video-stream0')
                ->setVideoStream(
                    (new VideoStream())->setH264(
                        (new VideoStream\H264CodecSettings())
                            ->setBitrateBps(550000)
                            ->setFrameRate(60)
                            ->setHeightPixels(360)
                            ->setWidthPixels(640)
                    )
                ),
            (new ElementaryStream())
                ->setKey('video-stream1')
                ->setVideoStream(
                    (new VideoStream())->setH264(
                        (new VideoStream\H264CodecSettings())
                            ->setBitrateBps(2500000)
                            ->setFrameRate(60)
                            ->setHeightPixels(720)
                            ->setWidthPixels(1280)
                    )
                ),
            (new ElementaryStream())
                ->setKey('audio-stream0')
                ->setAudioStream(
                    (new AudioStream())
                        ->setCodec('aac')
                        ->setBitrateBps(64000)
                )
        ])->setMuxStreams([
            (new MuxStream())
                ->setKey('sd')
                ->setContainer('mp4')
                ->setElementaryStreams(['video-stream0', 'audio-stream0']),
            (new MuxStream())
                ->setKey('hd')
                ->setContainer('mp4')
                ->setElementaryStreams(['video-stream1', 'audio-stream0'])
        ])
    );
    $request = (new CreateJobTemplateRequest())
        ->setParent($formattedParent)
        ->setJobTemplate($jobTemplate)
        ->setJobTemplateId($templateId);

    $response = $transcoderServiceClient->createJobTemplate($request);

    // Print job template name.
    printf('Job template: %s' . PHP_EOL, $response->getName());
}

Python

이 샘플을 사용해 보기 전에 Transcoder API 빠른 시작: 클라이언트 라이브러리 사용Python 설정 안내를 따르세요. 자세한 내용은 Transcoder API Python API 참조 문서를 확인하세요.

Transcoder API에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import argparse

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

def create_job_template(
    project_id: str,
    location: str,
    template_id: str,
) -> transcoder_v1.types.resources.JobTemplate:
    """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.

    Returns:
        The job template resource.
    """

    client = TranscoderServiceClient()

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

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

Ruby

이 샘플을 사용해 보기 전에 Transcoder API 빠른 시작: 클라이언트 라이브러리 사용Ruby 설정 안내를 따르세요. 자세한 내용은 Transcoder API Ruby API 참조 문서를 확인하세요.

Transcoder API에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

# project_id  = "YOUR-GOOGLE-CLOUD-PROJECT"  # (e.g. "my-project")
# location    = "YOUR-JOB-TEMPLATE-LOCATION"  # (e.g. "us-central1")
# template_id = "YOUR-JOB-TEMPLATE"  # (e.g. "my-job-template")

# Require the Transcoder client library.
require "google/cloud/video/transcoder"

# Create a Transcoder client.
client = Google::Cloud::Video::Transcoder.transcoder_service

# Build the resource name of the parent.
parent = client.location_path project: project_id, location: location

# Build the job template.
new_job_template = {
  config: {
    elementary_streams: [
      {
        key: "video-stream0",
        video_stream: {
          h264: {
            height_pixels: 360,
            width_pixels: 640,
            bitrate_bps: 550_000,
            frame_rate: 60
          }
        }
      },
      {
        key: "video-stream1",
        video_stream: {
          h264: {
            height_pixels: 720,
            width_pixels: 1280,
            bitrate_bps: 2_500_000,
            frame_rate: 60
          }
        }
      },
      {
        key: "audio-stream0",
        audio_stream: {
          codec: "aac",
          bitrate_bps: 64_000
        }
      }
    ],
    mux_streams: [
      {
        key: "sd",
        container: "mp4",
        elementary_streams: [
          "video-stream0",
          "audio-stream0"
        ]
      },
      {
        key: "hd",
        container: "mp4",
        elementary_streams: [
          "video-stream1",
          "audio-stream0"
        ]
      }
    ]
  }
}

job_template = client.create_job_template parent: parent, job_template: new_job_template, job_template_id: template_id

# Print the job template name.
puts "Job template: #{job_template.name}"

다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.