Create a channel event

Create a channel event to execute an operation on a channel resource without needing to stop the channel. For example, you can use a channel event to create ad break markers.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

C#

To learn how to install and use the client library for Live Stream API, see Live Stream API client libraries. For more information, see the Live Stream API C# API reference documentation.

To authenticate to Live Stream API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


using Google.Cloud.Video.LiveStream.V1;

public class CreateChannelEventSample
{
    public Event CreateChannelEvent(
         string projectId, string locationId, string channelId, string eventId)
    {
        // Create the client.
        LivestreamServiceClient client = LivestreamServiceClient.Create();

        CreateEventRequest request = new CreateEventRequest
        {
            ParentAsChannelName = ChannelName.FromProjectLocationChannel(projectId, locationId, channelId),
            EventId = eventId,
            Event = new Event
            {
                AdBreak = new Event.Types.AdBreakTask
                {
                    Duration = new Google.Protobuf.WellKnownTypes.Duration
                    {
                        Seconds = 30
                    }
                },
                ExecuteNow = true
            }
        };

        // Make the request.
        Event response = client.CreateEvent(request);
        return response;
    }
}

Go

To learn how to install and use the client library for Live Stream API, see Live Stream API client libraries. For more information, see the Live Stream API Go API reference documentation.

To authenticate to Live Stream API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import (
	"context"
	"fmt"
	"io"

	"github.com/golang/protobuf/ptypes/duration"

	livestream "cloud.google.com/go/video/livestream/apiv1"
	"cloud.google.com/go/video/livestream/apiv1/livestreampb"
)

// createChannelEvent creates a channel event. An event is a sub-resource of a
// channel, which can be scheduled by the user to execute operations on a
// channel resource without having to stop the channel. This sample creates an
// ad break event.
func createChannelEvent(w io.Writer, projectID, location, channelID, eventID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// channelID := "my-channel"
	// eventID := "my-channel-event"
	ctx := context.Background()
	client, err := livestream.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &livestreampb.CreateEventRequest{
		Parent:  fmt.Sprintf("projects/%s/locations/%s/channels/%s", projectID, location, channelID),
		EventId: eventID,
		Event: &livestreampb.Event{
			Task: &livestreampb.Event_AdBreak{
				AdBreak: &livestreampb.Event_AdBreakTask{
					Duration: &duration.Duration{
						Seconds: 30,
					},
				},
			},
			ExecuteNow: true,
		},
	}
	// Creates the channel event.
	response, err := client.CreateEvent(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateEvent: %w", err)
	}

	fmt.Fprintf(w, "Channel event: %v", response.Name)
	return nil
}

Java

To learn how to install and use the client library for Live Stream API, see Live Stream API client libraries. For more information, see the Live Stream API Java API reference documentation.

To authenticate to Live Stream API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import com.google.cloud.video.livestream.v1.ChannelName;
import com.google.cloud.video.livestream.v1.CreateEventRequest;
import com.google.cloud.video.livestream.v1.Event;
import com.google.cloud.video.livestream.v1.Event.AdBreakTask;
import com.google.cloud.video.livestream.v1.LivestreamServiceClient;
import com.google.protobuf.Duration;
import java.io.IOException;

public class CreateChannelEvent {

  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 channelId = "my-channel-id";
    String eventId = "my-channel-event-id";

    createChannelEvent(projectId, location, channelId, eventId);
  }

  public static void createChannelEvent(
      String projectId, String location, String channelId, String eventId) 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. In this example, try-with-resources is used
    // which automatically calls close() on the client to clean up resources.
    try (LivestreamServiceClient livestreamServiceClient = LivestreamServiceClient.create()) {
      var createEventRequest =
          CreateEventRequest.newBuilder()
              .setParent(ChannelName.of(projectId, location, channelId).toString())
              .setEventId(eventId)
              .setEvent(
                  Event.newBuilder()
                      .setAdBreak(
                          AdBreakTask.newBuilder()
                              .setDuration(Duration.newBuilder().setSeconds(30).build())
                              .build())
                      .setExecuteNow(true)
                      .build())
              .build();

      Event response = livestreamServiceClient.createEvent(createEventRequest);
      System.out.println("Channel event: " + response.getName());
    }
  }
}

Node.js

To learn how to install and use the client library for Live Stream API, see Live Stream API client libraries. For more information, see the Live Stream API Node.js API reference documentation.

To authenticate to Live Stream API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project-id';
// location = 'us-central1';
// channelId = 'my-channel';
// eventId = 'my-channel-event';

// Imports the Livestream library
const {LivestreamServiceClient} = require('@google-cloud/livestream').v1;

// Instantiates a client
const livestreamServiceClient = new LivestreamServiceClient();

async function createChannelEvent() {
  // Construct request
  const request = {
    parent: livestreamServiceClient.channelPath(
      projectId,
      location,
      channelId
    ),
    eventId: eventId,
    event: {
      adBreak: {
        duration: {
          seconds: 30,
        },
      },
      executeNow: true,
    },
  };

  // Run request
  const [event] = await livestreamServiceClient.createEvent(request);
  console.log(`Channel event: ${event.name}`);
}

createChannelEvent();

PHP

To learn how to install and use the client library for Live Stream API, see Live Stream API client libraries. For more information, see the Live Stream API PHP API reference documentation.

To authenticate to Live Stream API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

use Google\Cloud\Video\LiveStream\V1\Event;
use Google\Cloud\Video\LiveStream\V1\Client\LivestreamServiceClient;
use Google\Cloud\Video\LiveStream\V1\CreateEventRequest;
use Google\Protobuf\Duration;

/**
 * Creates a channel event. This particular sample inserts an ad break marker.
 * Other event types are supported.
 *
 * @param string  $callingProjectId   The project ID to run the API call under
 * @param string  $location           The location of the channel
 * @param string  $channelId          The ID of the channel
 * @param string  $eventId            The ID of the channel event
 */
function create_channel_event(
    string $callingProjectId,
    string $location,
    string $channelId,
    string $eventId
): void {
    // Instantiate a client.
    $livestreamClient = new LivestreamServiceClient();

    $parent = $livestreamClient->channelName($callingProjectId, $location, $channelId);

    $eventAdBreak = (new Event\AdBreakTask())
        ->setDuration(new Duration(['seconds' => 30]));
    $event = (new Event())
        ->setAdBreak($eventAdBreak)
        ->setExecuteNow(true);

    // Run the channel event creation request.
    $request = (new CreateEventRequest())
        ->setParent($parent)
        ->setEvent($event)
        ->setEventId($eventId);
    $response = $livestreamClient->createEvent($request);
    // Print results.
    printf('Channel event: %s' . PHP_EOL, $response->getName());
}

Python

To learn how to install and use the client library for Live Stream API, see Live Stream API client libraries. For more information, see the Live Stream API Python API reference documentation.

To authenticate to Live Stream API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import argparse

from google.cloud.video import live_stream_v1
from google.cloud.video.live_stream_v1.services.livestream_service import (
    LivestreamServiceClient,
)
from google.protobuf import duration_pb2 as duration


def create_channel_event(
    project_id: str, location: str, channel_id: str, event_id: str
) -> live_stream_v1.types.Event:
    """Creates a channel event.
    Args:
        project_id: The GCP project ID.
        location: The location of the channel.
        channel_id: The user-defined channel ID.
        event_id: The user-defined event ID."""

    client = LivestreamServiceClient()
    parent = f"projects/{project_id}/locations/{location}/channels/{channel_id}"
    name = f"projects/{project_id}/locations/{location}/channels/{channel_id}/events/{event_id}"

    event = live_stream_v1.types.Event(
        name=name,
        ad_break=live_stream_v1.types.Event.AdBreakTask(
            duration=duration.Duration(
                seconds=30,
            ),
        ),
        execute_now=True,
    )

    response = client.create_event(parent=parent, event=event, event_id=event_id)
    print(f"Channel event: {response.name}")

    return response

Ruby

To learn how to install and use the client library for Live Stream API, see Live Stream API client libraries. For more information, see the Live Stream API Ruby API reference documentation.

To authenticate to Live Stream API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

require "google/cloud/video/live_stream"

##
# Create a channel event
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param location [String] The location (e.g. "us-central1")
# @param channel_id [String] Your channel name (e.g. "my-channel")
# @param event_id [String] Your event name (e.g. "my-event")
#
def create_channel_event project_id:, location:, channel_id:, event_id:
  # Create a Live Stream client.
  client = Google::Cloud::Video::LiveStream.livestream_service

  # Build the resource name of the parent.
  parent = client.channel_path project: project_id, location: location, channel: channel_id

  # Set the event fields.
  new_event = {
    ad_break: {
      duration: {
        seconds: 100
      }
    },
    execute_now: true
  }

  response = client.create_event parent: parent, event: new_event, event_id: event_id

  # Print the channel event name.
  puts "Channel event: #{response.name}"
end

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.