使用 Transcoder API 將影片轉碼

本頁說明如何使用 Transcoder API 和 curl、Windows PowerShell 或用戶端程式庫的預設設定,建立基本影片轉碼工作。

您也可以使用下列任一程式設計語言,直接在 Google Cloud 主控台中執行本快速入門導覽課程:

事前準備

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. Install the Google Cloud CLI.

  3. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  4. To initialize the gcloud CLI, run the following command:

    gcloud init
  5. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Create local authentication credentials for your user account:

    gcloud auth application-default login

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

  8. Grant roles to your user account. Run the following command once for each of the following IAM roles: roles/transcoder.admin, roles/storage.admin

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:USER_IDENTIFIER" --role=ROLE
    • Replace PROJECT_ID with your project ID.
    • Replace USER_IDENTIFIER with the identifier for your user account. For example, user:myemail@example.com.

    • Replace ROLE with each individual role.
  9. Install the Google Cloud CLI.

  10. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  11. To initialize the gcloud CLI, run the following command:

    gcloud init
  12. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  13. Make sure that billing is enabled for your Google Cloud project.

  14. Create local authentication credentials for your user account:

    gcloud auth application-default login

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

  15. Grant roles to your user account. Run the following command once for each of the following IAM roles: roles/transcoder.admin, roles/storage.admin

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:USER_IDENTIFIER" --role=ROLE
    • Replace PROJECT_ID with your project ID.
    • Replace USER_IDENTIFIER with the identifier for your user account. For example, user:myemail@example.com.

    • Replace ROLE with each individual role.
  16. 建立 Cloud Storage 值區

    1. In the Google Cloud console, go to the Cloud Storage Buckets page.

      Go to Buckets

    2. Click Create.
    3. On the Create a bucket page, enter your bucket information. To go to the next step, click Continue.
      1. For Name your bucket, enter a unique bucket name. Don't include sensitive information in the bucket name, because the bucket namespace is global and publicly visible.
      2. In the Choose where to store your data section, do the following:
        1. Select a Location type.
        2. Choose a location where your bucket's data is permanently stored from the Location type drop-down menu.
        3. To set up cross-bucket replication, select Add cross-bucket replication via Storage Transfer Service and follow these steps:

          Set up cross-bucket replication

          1. In the Bucket menu, select a bucket.
          2. In the Replication settings section, click Configure to configure settings for the replication job.

            The Configure cross-bucket replication pane appears.

            • To filter objects to replicate by object name prefix, enter a prefix that you want to include or exclude objects from, then click Add a prefix.
            • To set a storage class for the replicated objects, select a storage class from the Storage class menu. If you skip this step, the replicated objects will use the destination bucket's storage class by default.
            • Click Done.
      3. In the Choose how to store your data section, do the following:
        1. In the Set a default class section, select the following: Standard.
        2. To enable hierarchical namespace, in the Optimize storage for data-intensive workloads section, select Enable hierarchical namespace on this bucket.
      4. In the Choose how to control access to objects section, select whether or not your bucket enforces public access prevention, and select an access control method for your bucket's objects.
      5. In the Choose how to protect object data section, do the following:
        • Select any of the options under Data protection that you want to set for your bucket.
          • To enable soft delete, click the Soft delete policy (For data recovery) checkbox, and specify the number of days you want to retain objects after deletion.
          • To set Object Versioning, click the Object versioning (For version control) checkbox, and specify the maximum number of versions per object and the number of days after which the noncurrent versions expire.
          • To enable the retention policy on objects and buckets, click the Retention (For compliance) checkbox, and then do the following:
            • To enable Object Retention Lock, click the Enable object retention checkbox.
            • To enable Bucket Lock, click the Set bucket retention policy checkbox, and choose a unit of time and a length of time for your retention period.
        • To choose how your object data will be encrypted, expand the Data encryption section (), and select a Data encryption method.
    4. Click Create.
    5. 按一下「Create Folder」(建立資料夾),然後輸入名稱,建立要儲存編碼影片輸出內容的資料夾。

使用 Transcoder API 將影片轉碼

您需要從本機電腦取得至少 5 秒長的影片,才能執行下列步驟 (範例影片)。請參閱支援的輸入和輸出格式清單

將影片上傳至 Cloud Storage 值區

  1. 前往 Google Cloud 控制台的「Cloud Storage 瀏覽器」頁面。
    前往 Cloud Storage 瀏覽器頁面
  2. 按一下值區名稱即可開啟。
  3. 按一下「上傳檔案」
  4. 從本機電腦選取要上傳的影片檔案。

影片現在已儲存至 Cloud Storage 值區。

建立轉碼工作

根據預設,Transcoder API 會使用 H.264 編碼和 MP4、HLS 和 MPEG-DASH 封裝,轉碼影片。為每部輸入的影片提供高畫質 (1280x720 像素) 和標準畫質 (640x360 像素) 的輸出版本。

如要建立工作,請使用 projects.locations.jobs.create 方法。以下程式碼範例會使用預設值建立基本轉碼工作。

REST

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_ID:您在 IAM 設定中列出的 Google Cloud 專案 ID。
  • LOCATION:工作執行的位置。使用支援的地區之一。
    顯示地區
    • us-central1
    • us-west1
    • us-west2
    • us-east1
    • us-east4
    • southamerica-east1
    • northamerica-northeast1
    • asia-east1
    • asia-northeast1
    • asia-northeast3
    • asia-south1
    • asia-southeast1
    • australia-southeast1
    • europe-west1
    • europe-west2
    • europe-west4
    • me-west1
    • me-central1
    • me-central2
  • STORAGE_BUCKET_NAME:您建立的 Cloud Storage 值區名稱。
  • STORAGE_INPUT_VIDEO:Cloud Storage 值區中要轉碼的影片名稱,例如 my-vid.mp4。這個欄位應考量到您在桶中建立的任何資料夾 (例如 input/my-vid.mp4)。
  • STORAGE_OUTPUT_FOLDER:您要儲存已編碼影片輸出的 Cloud Storage 資料夾名稱。

如要傳送要求,請展開以下其中一個選項:

這個特定的 REST 範例會使用選用的 fields 查詢參數,只在回應中顯示已建立的資源名稱。

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/jobs/JOB_ID"
}

gcloud

  1. 請為 gcloud 指令進行下列替換:
    • STORAGE_BUCKET_NAME:您建立的 Cloud Storage 值區名稱。
    • STORAGE_INPUT_VIDEO:Cloud Storage 值區中要轉碼的影片名稱,例如 my-vid.mp4。這個欄位應考量到您在資料夾中建立的任何資料夾 (例如 input/my-vid.mp4)。
    • LOCATION:工作執行的位置。使用支援的地區之一。
      顯示地區
      • us-central1
      • us-west1
      • us-west2
      • us-east1
      • us-east4
      • southamerica-east1
      • northamerica-northeast1
      • asia-east1
      • asia-northeast1
      • asia-northeast3
      • asia-south1
      • asia-southeast1
      • australia-southeast1
      • europe-west1
      • europe-west2
      • europe-west4
      • me-west1
      • me-central1
      • me-central2
    • STORAGE_OUTPUT_FOLDER:您要儲存已編碼影片輸出的 Cloud Storage 資料夾名稱。
  2. 請執行下列指令:
    gcloud transcoder jobs create \
      --input-uri="gs://STORAGE_BUCKET_NAME/STORAGE_INPUT_VIDEO" \
      --location=LOCATION \
      --output-uri="gs://STORAGE_BUCKET_NAME/STORAGE_OUTPUT_FOLDER/"
    您應該會看到類似以下的回應:
    {
      "config": {
       ...
      },
      "createTime": CREATE_TIME,
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/jobs/JOB_ID",
      "state": "PENDING",
      "ttlAfterCompletionDays": 30
    }
    

C#

在試用這個範例之前,請先按照 Transcoder API 快速入門:使用用戶端程式庫中的操作說明設定 C#。 詳情請參閱 Transcoder API C# API 參考說明文件

如要向 Transcoder API 驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


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

public class CreateJobFromPresetSample
{
    public Job CreateJobFromPreset(
        string projectId, string location, string inputUri, string outputUri, string preset)
    {
        // Create the client.
        TranscoderServiceClient client = TranscoderServiceClient.Create();

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

        // Build the job.
        Job newJob = new Job
        {
            InputUri = inputUri,
            OutputUri = outputUri,
            TemplateId = preset
        };

        // Call the API.
        Job job = client.CreateJob(parent, newJob);

        // Return the result.
        return job;
    }
}

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"
)

// createJobFromPreset creates a job based on a given preset template. See
// https://cloud.google.com/transcoder/docs/how-to/jobs#create_jobs_presets
// for more information.
func createJobFromPreset(w io.Writer, projectID string, location string, inputURI string, outputURI string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// inputURI := "gs://my-bucket/my-video-file"
	// outputURI := "gs://my-bucket/my-output-folder/"
	preset := "preset/web-hd"
	ctx := context.Background()
	client, err := transcoder.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &transcoderpb.CreateJobRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		Job: &transcoderpb.Job{
			InputUri:  inputURI,
			OutputUri: outputURI,
			JobConfig: &transcoderpb.Job_TemplateId{
				TemplateId: preset,
			},
		},
	}
	// Creates the job, Jobs take a variable amount of time to run.
	// You can query for the job state.
	response, err := client.CreateJob(ctx, req)
	if err != nil {
		return fmt.Errorf("createJobFromPreset: %w", err)
	}

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

Java

在試用這個範例之前,請先按照 Transcoder API 快速入門:使用用戶端程式庫中的操作說明設定 Java。 詳情請參閱 Transcoder API Java API 參考說明文件

如要向 Transcoder API 驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


import com.google.cloud.video.transcoder.v1.CreateJobRequest;
import com.google.cloud.video.transcoder.v1.Job;
import com.google.cloud.video.transcoder.v1.LocationName;
import com.google.cloud.video.transcoder.v1.TranscoderServiceClient;
import java.io.IOException;

public class CreateJobFromPreset {

  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 inputUri = "gs://my-bucket/my-video-file";
    String outputUri = "gs://my-bucket/my-output-folder/";
    // See https://cloud.google.com/transcoder/docs/concepts/overview#job_template
    // for information on this preset.
    String preset = "preset/web-hd";

    createJobFromPreset(projectId, location, inputUri, outputUri, preset);
  }

  // Creates a job from a preset.
  public static void createJobFromPreset(
      String projectId, String location, String inputUri, String outputUri, String preset)
      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()) {

      CreateJobRequest createJobRequest =
          CreateJobRequest.newBuilder()
              .setJob(
                  Job.newBuilder()
                      .setInputUri(inputUri)
                      .setOutputUri(outputUri)
                      .setTemplateId(preset)
                      .build())
              .setParent(LocationName.of(projectId, location).toString())
              .build();

      // Send the job creation request and process the response.
      Job job = transcoderServiceClient.createJob(createJobRequest);
      System.out.println("Job: " + job.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';
// inputUri = 'gs://my-bucket/my-video-file';
// outputUri = 'gs://my-bucket/my-output-folder/';
// preset = 'preset/web-hd';

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

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

async function createJobFromPreset() {
  // Construct request
  const request = {
    parent: transcoderServiceClient.locationPath(projectId, location),
    job: {
      inputUri: inputUri,
      outputUri: outputUri,
      templateId: preset,
    },
  };

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

createJobFromPreset();

PHP

在試用這個範例之前,請先按照 Transcoder API 快速入門:使用用戶端程式庫中的操作說明設定 PHP。 詳情請參閱 Transcoder API PHP API 參考說明文件

如要向 Transcoder API 驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

use Google\Cloud\Video\Transcoder\V1\Client\TranscoderServiceClient;
use Google\Cloud\Video\Transcoder\V1\CreateJobRequest;
use Google\Cloud\Video\Transcoder\V1\Job;

/**
 * Creates a job based on a job preset.
 *
 * @param string $projectId The ID of your Google Cloud Platform project.
 * @param string $location The location of the job.
 * @param string $inputUri Uri of the video in the Cloud Storage bucket.
 * @param string $outputUri Uri of the video output folder in the Cloud Storage bucket.
 * @param string $preset The preset template (for example, "preset/web-hd").
 */
function create_job_from_preset($projectId, $location, $inputUri, $outputUri, $preset)
{
    // Instantiate a client.
    $transcoderServiceClient = new TranscoderServiceClient();

    $formattedParent = $transcoderServiceClient->locationName($projectId, $location);
    $job = new Job();
    $job->setInputUri($inputUri);
    $job->setOutputUri($outputUri);
    $job->setTemplateId($preset);
    $request = (new CreateJobRequest())
        ->setParent($formattedParent)
        ->setJob($job);

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

    // Print job name.
    printf('Job: %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_from_preset(
    project_id: str,
    location: str,
    input_uri: str,
    output_uri: str,
    preset: str,
) -> transcoder_v1.types.resources.Job:
    """Creates a job based on a job preset.

    Args:
        project_id: The GCP project ID.
        location: The location to start the job in.
        input_uri: Uri of the video in the Cloud Storage bucket.
        output_uri: Uri of the video output folder in the Cloud Storage bucket.
        preset: The preset template (for example, 'preset/web-hd').

    Returns:
        The job resource.
    """

    client = TranscoderServiceClient()

    parent = f"projects/{project_id}/locations/{location}"
    job = transcoder_v1.types.Job()
    job.input_uri = input_uri
    job.output_uri = output_uri
    job.template_id = preset

    response = client.create_job(parent=parent, job=job)
    print(f"Job: {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-LOCATION"  # (e.g. "us-central1")
# input_uri   = "YOUR-GCS-INPUT-VIDEO"  # (e.g. "gs://my-bucket/my-video-file")
# output_uri  = "YOUR-GCS-OUTPUT-FOLDER/"  # (e.g. "gs://my-bucket/my-output-folder/")
# preset      = "YOUR-JOB-PRESET"  # (e.g. "preset/web-hd")

# 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

# Set the job fields.
new_job = {
  input_uri: input_uri,
  output_uri: output_uri,
  template_id: preset
}

job = client.create_job parent: parent, job: new_job

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

複製傳回的 JOB_ID。您需要這項資訊才能取得工作狀態。

查看轉碼工作狀態

如要查看工作狀態,請使用 projects.locations.jobs.get 方法。以下程式碼範例會取得工作詳細資料,然後顯示工作狀態。

REST

使用任何要求資料之前,請先替換以下項目:

  • JOB_ID:您建立的工作 ID。
  • PROJECT_ID:您的 Google Cloud 專案 ID。
  • LOCATION:工作的位置。使用支援的地區之一。
    顯示地區
    • us-central1
    • us-west1
    • us-west2
    • us-east1
    • us-east4
    • southamerica-east1
    • northamerica-northeast1
    • asia-east1
    • asia-northeast1
    • asia-northeast3
    • asia-south1
    • asia-southeast1
    • australia-southeast1
    • europe-west1
    • europe-west2
    • europe-west4
    • me-west1
    • me-central1
    • me-central2
  • 如要傳送要求,請展開以下其中一個選項:

    您應該會收到如下的 JSON 回應:

    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/jobs/JOB_ID",
      "config": {
        "inputs": [
          {
            "key": "input0",
            "uri": "gs://STORAGE_BUCKET_NAME/STORAGE_INPUT_VIDEO"
          }
        ],
        "editList": [
          {
            "key": "atom0",
            "inputs": [
              "input0"
            ],
            "startTimeOffset": "0s"
          }
        ],
        "elementaryStreams": [
          {
            "videoStream": {
              "h264": {
                "widthPixels": 640,
                "heightPixels": 360,
                "frameRate": 30,
                "bitrateBps": 550000,
                "pixelFormat": "yuv420p",
                "rateControlMode": "vbr",
                "crfLevel": 21,
                "gopDuration": "3s",
                "vbvSizeBits": 550000,
                "vbvFullnessBits": 495000,
                "entropyCoder": "cabac",
                "bFrameCount": 3,
                "aqStrength": 1,
                "profile": "high",
                "preset": "veryfast"
              }
            },
            "key": "video-stream0"
          },
          {
            "videoStream": {
              "h264": {
                "widthPixels": 1280,
                "heightPixels": 720,
                "frameRate": 30,
                "bitrateBps": 2500000,
                "pixelFormat": "yuv420p",
                "rateControlMode": "vbr",
                "crfLevel": 21,
                "gopDuration": "3s",
                "vbvSizeBits": 2500000,
                "vbvFullnessBits": 2250000,
                "entropyCoder": "cabac",
                "bFrameCount": 3,
                "aqStrength": 1,
                "profile": "high",
                "preset": "veryfast"
              }
            },
            "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"
            ]
          },
          {
            "key": "media-sd",
            "fileName": "media-sd.ts",
            "container": "ts",
            "elementaryStreams": [
              "video-stream0",
              "audio-stream0"
            ]
          },
          {
            "key": "media-hd",
            "fileName": "media-hd.ts",
            "container": "ts",
            "elementaryStreams": [
              "video-stream1",
              "audio-stream0"
            ]
          },
          {
            "key": "video-only-sd",
            "fileName": "video-only-sd.m4s",
            "container": "fmp4",
            "elementaryStreams": [
              "video-stream0"
            ]
          },
          {
            "key": "video-only-hd",
            "fileName": "video-only-hd.m4s",
            "container": "fmp4",
            "elementaryStreams": [
              "video-stream1"
            ]
          },
          {
            "key": "audio-only",
            "fileName": "audio-only.m4s",
            "container": "fmp4",
            "elementaryStreams": [
              "audio-stream0"
            ]
          }
        ],
        "manifests": [
          {
            "fileName": "manifest.m3u8",
            "type": "HLS",
            "muxStreams": [
              "media-sd",
              "media-hd"
            ]
          },
          {
            "fileName": "manifest.mpd",
            "type": "DASH",
            "muxStreams": [
              "video-only-sd",
              "video-only-hd",
              "audio-only"
            ]
          }
        ],
        "output": {
          "uri": "gs://STORAGE_BUCKET_NAME/STORAGE_OUTPUT_FOLDER/"
        }
      },
      "state": "PENDING",
      "createTime": CREATE_TIME,
      "ttlAfterCompletionDays": 30
    }
    

    gcloud

    1. 請為 gcloud 指令進行下列替換:
      • JOB_ID:您建立的工作 ID。
      • LOCATION:工作的位置。使用支援的地區之一。
        顯示地區
        • us-central1
        • us-west1
        • us-west2
        • us-east1
        • us-east4
        • southamerica-east1
        • northamerica-northeast1
        • asia-east1
        • asia-northeast1
        • asia-northeast3
        • asia-south1
        • asia-southeast1
        • australia-southeast1
        • europe-west1
        • europe-west2
        • europe-west4
        • me-west1
        • me-central1
        • me-central2
    2. 執行下列指令:
      gcloud transcoder jobs describe JOB_ID --location=LOCATION
      您應該會看到類似以下的回應:
      {
        "name": "projects/PROJECT_NUMBER/locations/LOCATION/jobs/JOB_ID",
        "config": {
          "inputs": [
            {
              "key": "input0",
              "uri": "gs://STORAGE_BUCKET_NAME/STORAGE_INPUT_VIDEO"
            }
          ],
          "editList": [
            {
              "key": "atom0",
              "inputs": [
                "input0"
              ],
              "startTimeOffset": "0s"
            }
          ],
          "elementaryStreams": [
            {
              "videoStream": {
                "h264": {
                  "widthPixels": 640,
                  "heightPixels": 360,
                  "frameRate": 30,
                  "bitrateBps": 550000,
                  "pixelFormat": "yuv420p",
                  "rateControlMode": "vbr",
                  "crfLevel": 21,
                  "gopDuration": "3s",
                  "vbvSizeBits": 550000,
                  "vbvFullnessBits": 495000,
                  "entropyCoder": "cabac",
                  "bFrameCount": 3,
                  "aqStrength": 1,
                  "profile": "high",
                  "preset": "veryfast"
                }
              },
              "key": "video-stream0"
            },
            {
              "videoStream": {
                "h264": {
                  "widthPixels": 1280,
                  "heightPixels": 720,
                  "frameRate": 30,
                  "bitrateBps": 2500000,
                  "pixelFormat": "yuv420p",
                  "rateControlMode": "vbr",
                  "crfLevel": 21,
                  "gopDuration": "3s",
                  "vbvSizeBits": 2500000,
                  "vbvFullnessBits": 2250000,
                  "entropyCoder": "cabac",
                  "bFrameCount": 3,
                  "aqStrength": 1,
                  "profile": "high",
                  "preset": "veryfast"
                }
              },
              "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"
              ]
            },
            {
              "key": "media-sd",
              "fileName": "media-sd.ts",
              "container": "ts",
              "elementaryStreams": [
                "video-stream0",
                "audio-stream0"
              ]
            },
            {
              "key": "media-hd",
              "fileName": "media-hd.ts",
              "container": "ts",
              "elementaryStreams": [
                "video-stream1",
                "audio-stream0"
              ]
            },
            {
              "key": "video-only-sd",
              "fileName": "video-only-sd.m4s",
              "container": "fmp4",
              "elementaryStreams": [
                "video-stream0"
              ]
            },
            {
              "key": "video-only-hd",
              "fileName": "video-only-hd.m4s",
              "container": "fmp4",
              "elementaryStreams": [
                "video-stream1"
              ]
            },
            {
              "key": "audio-only",
              "fileName": "audio-only.m4s",
              "container": "fmp4",
              "elementaryStreams": [
                "audio-stream0"
              ]
            }
          ],
          "manifests": [
            {
              "fileName": "manifest.m3u8",
              "type": "HLS",
              "muxStreams": [
                "media-sd",
                "media-hd"
              ]
            },
            {
              "fileName": "manifest.mpd",
              "type": "DASH",
              "muxStreams": [
                "video-only-sd",
                "video-only-hd",
                "audio-only"
              ]
            }
          ],
          "output": {
            "uri": "gs://STORAGE_BUCKET_NAME/STORAGE_OUTPUT_FOLDER/"
          }
        },
        "state": "PENDING",
        "createTime": CREATE_TIME,
        "ttlAfterCompletionDays": 30
      }
      

    C#

    在試用這個範例之前,請先按照 Transcoder API 快速入門:使用用戶端程式庫中的操作說明設定 C#。 詳情請參閱 Transcoder API C# API 參考說明文件

    如要向 Transcoder API 驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

    
    using Google.Cloud.Video.Transcoder.V1;
    
    public class GetJobStateSample
    {
        public Job.Types.ProcessingState GetJobState(string projectId, string location, string jobId)
        {
            // Create the client.
            TranscoderServiceClient client = TranscoderServiceClient.Create();
    
            // Build the job name.
            JobName jobName = JobName.FromProjectLocationJob(projectId, location, jobId);
    
            // Call the API.
            Job job = client.GetJob(jobName);
    
            // Return the result.
            return job.State;
        }
    }

    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"
    )
    
    // getJobState gets the state for a previously-created job. See
    // https://cloud.google.com/transcoder/docs/how-to/jobs#check_job_status for
    // more information.
    func getJobState(w io.Writer, projectID string, location string, jobID string) error {
    	// projectID := "my-project-id"
    	// location := "us-central1"
    	// jobID := "my-job-id"
    	ctx := context.Background()
    	client, err := transcoder.NewClient(ctx)
    	if err != nil {
    		return fmt.Errorf("NewClient: %w", err)
    	}
    	defer client.Close()
    
    	req := &transcoderpb.GetJobRequest{
    		Name: fmt.Sprintf("projects/%s/locations/%s/jobs/%s", projectID, location, jobID),
    	}
    
    	response, err := client.GetJob(ctx, req)
    	if err != nil {
    		return fmt.Errorf("GetJob: %w", err)
    	}
    	fmt.Fprintf(w, "Job state: %v\n----\nJob failure reason:%v\n", response.State, response.Error)
    	return nil
    }
    

    Java

    在試用這個範例之前,請先按照 Transcoder API 快速入門:使用用戶端程式庫中的操作說明設定 Java。 詳情請參閱 Transcoder API Java API 參考說明文件

    如要向 Transcoder API 驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

    
    import com.google.cloud.video.transcoder.v1.GetJobRequest;
    import com.google.cloud.video.transcoder.v1.Job;
    import com.google.cloud.video.transcoder.v1.JobName;
    import com.google.cloud.video.transcoder.v1.TranscoderServiceClient;
    import java.io.IOException;
    
    public class GetJobState {
    
      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 jobId = "my-job-id";
    
        getJobState(projectId, location, jobId);
      }
    
      // Gets the state of a job.
      public static void getJobState(String projectId, String location, String jobId)
          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()) {
          JobName jobName =
              JobName.newBuilder().setProject(projectId).setLocation(location).setJob(jobId).build();
          GetJobRequest getJobRequest = GetJobRequest.newBuilder().setName(jobName.toString()).build();
    
          // Send the get job request and process the response.
          Job job = transcoderServiceClient.getJob(getJobRequest);
          System.out.println("Job state: " + job.getState());
        }
      }
    }

    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';
    // jobId = 'my-job-id';
    
    // Imports the Transcoder library
    const {TranscoderServiceClient} =
      require('@google-cloud/video-transcoder').v1;
    
    // Instantiates a client
    const transcoderServiceClient = new TranscoderServiceClient();
    
    async function getJob() {
      // Construct request
      const request = {
        name: transcoderServiceClient.jobPath(projectId, location, jobId),
      };
      const [response] = await transcoderServiceClient.getJob(request);
      console.log(`Job state: ${response.state}`);
    }
    
    getJob();

    PHP

    在試用這個範例之前,請先按照 Transcoder API 快速入門:使用用戶端程式庫中的操作說明設定 PHP。 詳情請參閱 Transcoder API PHP API 參考說明文件

    如要向 Transcoder API 驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

    use Google\Cloud\Video\Transcoder\V1\Client\TranscoderServiceClient;
    use Google\Cloud\Video\Transcoder\V1\GetJobRequest;
    use Google\Cloud\Video\Transcoder\V1\Job;
    
    /**
     * Gets a Transcoder job's state.
     *
     * @param string $projectId The ID of your Google Cloud Platform project.
     * @param string $location The location of the job.
     * @param string $jobId The job ID.
     */
    function get_job_state($projectId, $location, $jobId)
    {
        // Instantiate a client.
        $transcoderServiceClient = new TranscoderServiceClient();
    
        $formattedName = $transcoderServiceClient->jobName($projectId, $location, $jobId);
        $request = (new GetJobRequest())
            ->setName($formattedName);
        $job = $transcoderServiceClient->getJob($request);
    
        // Print job state.
        printf('Job state: %s' . PHP_EOL, Job\ProcessingState::name($job->getState()));
    }

    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 get_job_state(
        project_id: str,
        location: str,
        job_id: str,
    ) -> transcoder_v1.types.resources.Job:
        """Gets a job's state.
    
        Args:
            project_id: The GCP project ID.
            location: The location this job is in.
            job_id: The job ID.
    
        Returns:
            The job resource.
        """
    
        client = TranscoderServiceClient()
    
        name = f"projects/{project_id}/locations/{location}/jobs/{job_id}"
        response = client.get_job(name=name)
    
        print(f"Job state: {str(response.state.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-LOCATION"  # (e.g. "us-central1")
    # job_id     = "YOUR-JOB-ID"  # (e.g. "c82c295b-3f5a-47df-8562-938a89d40fd0")
    
    # 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 job.
    name = client.job_path project: project_id, location: location, job: job_id
    
    # Get the job.
    job = client.get_job name: name
    
    # Print the job state.
    puts "Job state: #{job.state}"

    ���果 stateSUCCEEDED,表示工作已完成,且影片輸出內容現在已可在 Cloud Storage 值區的已編碼檔案清單中取得。

    播放影片

    如要在 Shaka Player 中播放產生的媒體檔案,請完成下列步驟:

    1. 將您建立的 Cloud Storage bucket 設為可公開讀取
    2. 如要在 Cloud Storage 值區中啟用跨來源資源共享 (CORS),請按照下列步驟操作:
      1. 建立包含下列內容的 JSON 檔案:
        [
          {
            "origin": ["https://shaka-player-demo.appspot.com/"],
            "responseHeader": ["Content-Type", "Range"],
            "method": ["GET", "HEAD"],
            "maxAgeSeconds": 3600
          }
        ]
      2. JSON_FILE_NAME 替換為您在前一個步驟中建立的 JSON 檔案名稱,然後執行下列指令:
        gcloud storage buckets update gs://STORAGE_BUCKET_NAME --cors-file=JSON_FILE_NAME.json
    3. 在 Cloud Storage 值區中,選取轉碼工作產生的 MP4 或資訊清單檔案。在該檔案的「Public access」(公開存取權) 資料欄中,按一下「Copy URL」(複製網址)
    4. 前往 Shaka Player (這是一個線上即時串流播放器)。
    5. 按一下頂端導覽列中的「Custom Content」(自訂內容)
    6. 按一下「+」按鈕。
    7. 將檔案的公開網址貼到「Manifest URL」(資訊清單網址) 方塊中。

      在 Shaka Player 中輸入檔案網址。

    8. 在「Name」(名稱) 方塊中輸入名稱。

    9. 按一下「Save」(儲存)

    10. 按一下「Play」(播放)

    清除所用資源

    如要避免系統向您的 Google Cloud 帳戶收取您在本頁所用資源的費用,請按照下列步驟操作。

    刪除值區

    1. 前往 Google Cloud 控制台的「Cloud Storage 瀏覽器」頁面。

      前往 Cloud Storage 瀏覽器頁面

    2. 找出您建立的值區,並選取旁邊的核取方塊。

    3. 點選「刪除」。

    4. 在出現的彈出式視窗中,按一下「Delete」(刪除),即可永久刪除值區及其內容。

    刪除工作

    REST

    使用任何要求資料之前,請先替換以下項目:

  • JOB_ID:您建立的工作 ID。
  • PROJECT_ID:您的 Google Cloud 專案 ID。
  • LOCATION:工作的位置。使用支援的地區之一。
    顯示地區
    • us-central1
    • us-west1
    • us-west2
    • us-east1
    • us-east4
    • southamerica-east1
    • northamerica-northeast1
    • asia-east1
    • asia-northeast1
    • asia-northeast3
    • asia-south1
    • asia-southeast1
    • australia-southeast1
    • europe-west1
    • europe-west2
    • europe-west4
    • me-west1
    • me-central1
    • me-central2
  • 如要傳送要求,請展開以下其中一個選項:

    您應該會收到如下的 JSON 回應:

    {}
    

    gcloud

    1. 請為 gcloud 指令進行下列替換:
      • JOB_ID:您建立的工作 ID。
      • LOCATION:工作的位置。使用支援的地區之一。
        顯示地區
        • us-central1
        • us-west1
        • us-west2
        • us-east1
        • us-east4
        • southamerica-east1
        • northamerica-northeast1
        • asia-east1
        • asia-northeast1
        • asia-northeast3
        • asia-south1
        • asia-southeast1
        • australia-southeast1
        • europe-west1
        • europe-west2
        • europe-west4
        • me-west1
        • me-central1
        • me-central2
    2. 執行下列指令:
      gcloud transcoder jobs delete JOB_ID --location=LOCATION
      您應該會看到類似以下的回應:
      Deleted job [projects/PROJECT_ID/locations/LOCATION/jobs/JOB_ID].
      

    C#

    在試用這個範例之前,請先按照 Transcoder API 快速入門:使用用戶端程式庫中的操作說明設定 C#。 詳情請參閱 Transcoder API C# API 參考說明文件

    如要向 Transcoder API 驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

    
    using Google.Cloud.Video.Transcoder.V1;
    
    public class DeleteJobSample
    {
        public void DeleteJob(string projectId, string location, string jobId)
        {
            // Create the client.
            TranscoderServiceClient client = TranscoderServiceClient.Create();
    
            // Build the job name.
            JobName jobName = JobName.FromProjectLocationJob(projectId, location, jobId);
    
            // Call the API.
            client.DeleteJob(jobName);
        }
    }

    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"
    )
    
    // deleteJob deletes a previously-created job. See
    // https://cloud.google.com/transcoder/docs/how-to/jobs#delete_jobs for more
    // information.
    func deleteJob(w io.Writer, projectID string, location string, jobID string) error {
    	// projectID := "my-project-id"
    	// location := "us-central1"
    	// jobID := "my-job-id"
    	ctx := context.Background()
    	client, err := transcoder.NewClient(ctx)
    	if err != nil {
    		return fmt.Errorf("NewClient: %w", err)
    	}
    	defer client.Close()
    
    	req := &transcoderpb.DeleteJobRequest{
    		Name: fmt.Sprintf("projects/%s/locations/%s/jobs/%s", projectID, location, jobID),
    	}
    
    	err = client.DeleteJob(ctx, req)
    	if err != nil {
    		return fmt.Errorf("DeleteJob: %w", err)
    	}
    
    	fmt.Fprintf(w, "Deleted job")
    	return nil
    }
    

    Java

    在試用這個範例之前,請先按照 Transcoder API 快速入門:使用用戶端程式庫中的操作說明設定 Java。 詳情請參閱 Transcoder API Java API 參考說明文件

    如要向 Transcoder API 驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

    
    import com.google.cloud.video.transcoder.v1.DeleteJobRequest;
    import com.google.cloud.video.transcoder.v1.JobName;
    import com.google.cloud.video.transcoder.v1.TranscoderServiceClient;
    import java.io.IOException;
    
    public class DeleteJob {
    
      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 jobId = "my-job-id";
    
        deleteJob(projectId, location, jobId);
      }
    
      // Deletes a job.
      public static void deleteJob(String projectId, String location, String jobId) 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()) {
          JobName jobName =
              JobName.newBuilder().setProject(projectId).setLocation(location).setJob(jobId).build();
          DeleteJobRequest deleteJobRequest = DeleteJobRequest.newBuilder().setName(jobName.toString())
              .build();
    
          // Send the delete job request and process the response.
          transcoderServiceClient.deleteJob(deleteJobRequest);
          System.out.println("Deleted job");
        }
      }
    }

    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';
    // jobId = 'my-job-id';
    
    // Imports the Transcoder library
    const {TranscoderServiceClient} =
      require('@google-cloud/video-transcoder').v1;
    
    // Instantiates a client
    const transcoderServiceClient = new TranscoderServiceClient();
    
    async function deleteJob() {
      // Construct request
      const request = {
        name: transcoderServiceClient.jobPath(projectId, location, jobId),
      };
      await transcoderServiceClient.deleteJob(request);
      console.log('Deleted job');
    }
    
    deleteJob();

    PHP

    在試用這個範例之前,請先按照 Transcoder API 快速入門:使用用戶端程式庫中的操作說明設定 PHP。 詳情請參閱 Transcoder API PHP API 參考說明文件

    如要向 Transcoder API 驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

    use Google\Cloud\Video\Transcoder\V1\Client\TranscoderServiceClient;
    use Google\Cloud\Video\Transcoder\V1\DeleteJobRequest;
    
    /**
     * Deletes a Transcoder job.
     *
     * @param string $projectId The ID of your Google Cloud Platform project.
     * @param string $location The location of the job.
     * @param string $jobId The job ID.
     */
    function delete_job($projectId, $location, $jobId)
    {
        // Instantiate a client.
        $transcoderServiceClient = new TranscoderServiceClient();
    
        $formattedName = $transcoderServiceClient->jobName($projectId, $location, $jobId);
        $request = (new DeleteJobRequest())
            ->setName($formattedName);
        $transcoderServiceClient->deleteJob($request);
    
        print('Deleted job' . PHP_EOL);
    }

    Python

    在試用這個範例之前,請先按照 Transcoder API 快速入門:使用用戶端程式庫中的操作說明設定 Python。 詳情請參閱 Transcoder API Python API 參考說明文件

    如要向 Transcoder API 驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

    
    import argparse
    
    from google.cloud.video.transcoder_v1.services.transcoder_service import (
        TranscoderServiceClient,
    )
    
    
    def delete_job(
        project_id: str,
        location: str,
        job_id: str,
    ) -> None:
        """Gets a job.
    
        Args:
            project_id: The GCP project ID.
            location: The location this job is in.
            job_id: The job ID."""
    
        client = TranscoderServiceClient()
    
        name = f"projects/{project_id}/locations/{location}/jobs/{job_id}"
        response = client.delete_job(name=name)
        print("Deleted job")
        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-LOCATION"  # (e.g. "us-central1")
    # job_id     = "YOUR-JOB-ID"  # (e.g. "c82c295b-3f5a-47df-8562-938a89d40fd0")
    
    # 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 job.
    name = client.job_path project: project_id, location: location, job: job_id
    
    # Delete the job.
    client.delete_job name: name
    
    # Print a success message.
    puts "Deleted job"

    撤銷憑證

    1. Optional: Revoke the authentication credentials that you created, and delete the local credential file.

      gcloud auth application-default revoke
    2. Optional: Revoke credentials from the gcloud CLI.

      gcloud auth revoke

    後續步驟