Crie um job de transcodificação definindo os valores para a configuração do job em vez de referenciar um modelo ou predefinição de um job.
Páginas de documentação que incluem esta amostra de código
Para visualizar o exemplo de código usado em contexto, consulte a seguinte documentação:
Amostra de código
C#
Antes de testar esta amostra, siga as instruções de configuração do C# no Guia de início rápido da API Transcoder: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Transcoder para C#.
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Video.Transcoder.V1;
public class CreateJobFromAdHocSample
{
public Job CreateJobFromAdHoc(
string projectId, string location, string inputUri, string outputUri)
{
// Create the client.
TranscoderServiceClient client = TranscoderServiceClient.Create();
// Build the parent location name.
LocationName parent = new LocationName(projectId, location);
// Build the job 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" }
};
Input input = new Input
{
Key = "input0",
Uri = inputUri
};
Output output = new Output
{
Uri = outputUri
};
JobConfig jobConfig = new JobConfig
{
Inputs = { input },
Output = output,
ElementaryStreams = { elementaryStream0, elementaryStream1, elementaryStream2 },
MuxStreams = { muxStream0, muxStream1 }
};
// Build the job.
Job newJob = new Job
{
Config = jobConfig,
InputUri = inputUri,
OutputUri = outputUri
};
// Call the API.
Job job = client.CreateJob(parent, newJob);
// Return the result.
return job;
}
}
Go
Antes de testar esta amostra, siga as instruções de configuração do Go no Guia de início rápido da API Transcoder: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Transcoder Go
import (
"context"
"fmt"
"io"
transcoder "cloud.google.com/go/video/transcoder/apiv1"
transcoderpb "google.golang.org/genproto/googleapis/cloud/video/transcoder/v1"
)
// createJobFromAdHoc creates a job based on a given configuration. See
// https://cloud.google.com/transcoder/docs/how-to/jobs#create_jobs_ad_hoc
// for more information.
func createJobFromAdHoc(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/"
ctx := context.Background()
client, err := transcoder.NewClient(ctx)
if err != nil {
return fmt.Errorf("NewClient: %v", 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_Config{
Config: &transcoderpb.JobConfig{
ElementaryStreams: []*transcoderpb.ElementaryStream{
&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,
},
},
},
},
},
&transcoderpb.ElementaryStream{
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,
},
},
},
},
},
&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"},
},
},
},
},
},
}
// 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("createJobFromAdHoc: %v", err)
}
fmt.Fprintf(w, "Job: %v", response.GetName())
return nil
}
Java
Antes de testar esta amostra, siga as instruções de configuração do Java no Guia de início rápido da API Transcoder: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Transcoder para Java.
import com.google.cloud.video.transcoder.v1.AudioStream;
import com.google.cloud.video.transcoder.v1.CreateJobRequest;
import com.google.cloud.video.transcoder.v1.ElementaryStream;
import com.google.cloud.video.transcoder.v1.Input;
import com.google.cloud.video.transcoder.v1.Job;
import com.google.cloud.video.transcoder.v1.JobConfig;
import com.google.cloud.video.transcoder.v1.LocationName;
import com.google.cloud.video.transcoder.v1.MuxStream;
import com.google.cloud.video.transcoder.v1.Output;
import com.google.cloud.video.transcoder.v1.TranscoderServiceClient;
import com.google.cloud.video.transcoder.v1.VideoStream;
import com.google.cloud.video.transcoder.v1.VideoStream.H264CodecSettings;
import java.io.IOException;
public class CreateJobFromAdHoc {
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/";
createJobFromAdHoc(projectId, location, inputUri, outputUri);
}
// Creates a job from an ad-hoc configuration.
public static void createJobFromAdHoc(
String projectId, String location, String inputUri, String outputUri) 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(
H264CodecSettings.newBuilder()
.setBitrateBps(550000)
.setFrameRate(60)
.setHeightPixels(360)
.setWidthPixels(640))
.build();
VideoStream videoStream1 =
VideoStream.newBuilder()
.setH264(
H264CodecSettings.newBuilder()
.setBitrateBps(2500000)
.setFrameRate(60)
.setHeightPixels(720)
.setWidthPixels(1280))
.build();
AudioStream audioStream0 =
AudioStream.newBuilder().setCodec("aac").setBitrateBps(64000).build();
JobConfig config =
JobConfig.newBuilder()
.addInputs(Input.newBuilder().setKey("input0").setUri(inputUri))
.setOutput(Output.newBuilder().setUri(outputUri))
.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 createJobRequest =
CreateJobRequest.newBuilder()
.setJob(
Job.newBuilder()
.setInputUri(inputUri)
.setOutputUri(outputUri)
.setConfig(config)
.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
Antes de tentar esse exemplo, siga as instruções de configuração do Node.js no Guia de início rápido da API Transcoder: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Transcoder Node.js
/**
* 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/';
// Imports the Transcoder library
const {TranscoderServiceClient} =
require('@google-cloud/video-transcoder').v1;
// Instantiates a client
const transcoderServiceClient = new TranscoderServiceClient();
async function createJobFromAdHoc() {
// Construct request
const request = {
parent: transcoderServiceClient.locationPath(projectId, location),
job: {
inputUri: inputUri,
outputUri: outputUri,
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 [response] = await transcoderServiceClient.createJob(request);
console.log(`Job: ${response.name}`);
}
createJobFromAdHoc();
PHP
Antes de testar esta amostra, siga as instruções de configuração do PHP no Guia de início rápido da API Transcoder: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Transcoder para PHP.
use Google\Cloud\Video\Transcoder\V1\AudioStream;
use Google\Cloud\Video\Transcoder\V1\ElementaryStream;
use Google\Cloud\Video\Transcoder\V1\Job;
use Google\Cloud\Video\Transcoder\V1\JobConfig;
use Google\Cloud\Video\Transcoder\V1\MuxStream;
use Google\Cloud\Video\Transcoder\V1\TranscoderServiceClient;
use Google\Cloud\Video\Transcoder\V1\VideoStream;
/**
* Creates a job based on an ad-hoc job configuration.
*
* @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.
*/
function create_job_from_ad_hoc($projectId, $location, $inputUri, $outputUri)
{
// Instantiate a client.
$transcoderServiceClient = new TranscoderServiceClient();
$formattedParent = $transcoderServiceClient->locationName($projectId, $location);
$jobConfig =
(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'])
]);
$job = (new Job())
->setInputUri($inputUri)
->setOutputUri($outputUri)
->setConfig($jobConfig);
$response = $transcoderServiceClient->createJob($formattedParent, $job);
// Print job name.
printf('Job: %s' . PHP_EOL, $response->getName());
}
Python
Antes de testar esta amostra, siga as instruções de configuração do Python no Guia de início rápido da API Transcoder: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Transcoder Python
import argparse
from google.cloud.video import transcoder_v1
from google.cloud.video.transcoder_v1.services.transcoder_service import (
TranscoderServiceClient,
)
def create_job_from_ad_hoc(project_id, location, input_uri, output_uri):
"""Creates a job based on an ad-hoc job configuration.
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."""
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.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(parent=parent, job=job)
print(f"Job: {response.name}")
return response
Ruby
Antes de testar esta amostra, siga as instruções de configuração do Ruby no Guia de início rápido da API Transcoder: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Transcoder para Ruby.
# 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/")
# 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 config.
new_job = {
input_uri: input_uri,
output_uri: output_uri,
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 = client.create_job parent: parent, job: new_job
# Print the job name.
puts "Job: #{job.name}"
A seguir
Para pesquisar e filtrar exemplos de código de outros produtos do Google Cloud, consulte o navegador de exemplos do Google Cloud.