You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过YouTube API为私密YouTube视频添加参与者及实现私密直播

Hey there! Let's tackle your two YouTube API needs using the OAuth foundation you already have laid out. I'll break each requirement down with actionable code snippets and key notes to avoid common pitfalls.

1. Adding Participants to a Private YouTube Video via API

To grant access to a private YouTube video for specific users, you'll use the YouTube Data API v3's videos.update endpoint. This lets you modify the video's privacy settings to include allowed viewers.

Key Prerequisites

  • Ensure your OAuth2 client has the https://www.googleapis.com/auth/youtube.force-ssl scope (required for modifying video privacy settings).
  • You'll need the target video's ID and the email addresses of users you want to add (must be valid Google accounts).

Updated Code Snippet

Building on your existing OAuth setup:

const {google} = require('googleapis');
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2(
  'YOUR_CLIENT_ID',
  'YOUR_CLIENT_SECRET',
  'YOUR_REDIRECT_URL'
);

oauth2Client.setCredentials({
  access_token: 'YOUR_ACCESS_TOKEN',
  refresh_token: 'YOUR_REFRESH_TOKEN'
});

oauth2Client.refreshAccessToken((err, tokens) => {
  if (err) console.error('Token refresh error:', err);
});

const youtube = google.youtube({
  version: 'v3',
  auth: oauth2Client
});

// Add participants to a private video
async function addVideoParticipants(videoId, allowedUsers) {
  try {
    // First, fetch existing allowed users if you want to append (not replace)
    const existingVideo = await youtube.videos.list({
      part: 'status',
      id: videoId
    });
    const currentAllowedUsers = existingVideo.data.items[0].status.privateVideoOptions?.allowedUsers || [];
    
    // Merge existing and new users (avoid duplicates)
    const updatedAllowedUsers = [...new Set([...currentAllowedUsers, ...allowedUsers])];

    // Update the video's privacy settings
    const response = await youtube.videos.update({
      part: 'status',
      requestBody: {
        id: videoId,
        status: {
          privacyStatus: 'private',
          privateVideoOptions: {
            allowedUsers: updatedAllowedUsers
          }
        }
      }
    });
    console.log('Participants added successfully:', response.data);
  } catch (err) {
    console.error('Error adding participants:', err);
  }
}

// Example usage: Replace with your video ID and user emails
addVideoParticipants('YOUR_PRIVATE_VIDEO_ID', ['user1@example.com', 'user2@example.com']);

Notes

  • If you skip fetching existing users, the allowedUsers array will replace the current list (not append). Use the merge step to avoid removing existing access.
  • Users will receive an email notification about access to the private video.
2. Starting a Private Live Stream via YouTube API

Setting up a private live stream involves three core steps: creating a live stream (the ingestion endpoint), creating a private broadcast (the public-facing stream entity), and binding them together.

Key Prerequisites

  • Required OAuth scopes: https://www.googleapis.com/auth/youtube (or the more restrictive https://www.googleapis.com/auth/youtube.force-ssl + https://www.googleapis.com/auth/youtube.readonly).
  • You'll need a tool like OBS or Streamlabs to push video to the RTMP URL generated by the API.

Updated Code Snippet

Again, building on your existing OAuth setup:

// Create and start a private live stream
async function createPrivateLiveStream() {
  try {
    // Step 1: Create a live stream (ingestion endpoint)
    const streamResponse = await youtube.liveStreams.insert({
      part: 'snippet,cdn',
      requestBody: {
        snippet: {
          title: 'My Private Live Stream'
        },
        cdn: {
          format: '1080p',
          ingestionType: 'rtmp'
        }
      }
    });
    const streamId = streamResponse.data.id;
    const rtmpUrl = `${streamResponse.data.cdn.ingestionInfo.ingestionAddress}/${streamResponse.data.cdn.ingestionInfo.streamName}`;
    console.log('Created live stream. RTMP URL:', rtmpUrl);

    // Step 2: Create a private broadcast
    const broadcastResponse = await youtube.liveBroadcasts.insert({
      part: 'snippet,status',
      requestBody: {
        snippet: {
          title: 'My Private Broadcast',
          scheduledStartTime: new Date().toISOString() // Start immediately, or set a future ISO date
        },
        status: {
          privacyStatus: 'private',
          privateVideoOptions: {
            allowedUsers: ['user1@example.com'] // Users allowed to view the stream
          }
        }
      }
    });
    const broadcastId = broadcastResponse.data.id;
    console.log('Created private broadcast:', broadcastId);

    // Step 3: Bind the stream to the broadcast
    await youtube.liveBroadcasts.bind({
      id: broadcastId,
      part: 'id',
      streamId: streamId
    });
    console.log('Stream bound to broadcast successfully');

    // Step 4: Start the broadcast (skip if scheduling for later)
    await youtube.liveBroadcasts.transition({
      id: broadcastId,
      part: 'status',
      broadcastStatus: 'live'
    });
    console.log('Broadcast is now live!');
  } catch (err) {
    console.error('Error creating private live stream:', err);
  }
}

// Example usage
createPrivateLiveStream();

Notes

  • The scheduledStartTime can be set to a future ISO 8601 date if you want to schedule a live stream in advance.
  • The RTMP URL is generated when you create the live stream—use this URL in your streaming software to push video content.
  • You can update allowed users for the broadcast later using liveBroadcasts.update with the status.privateVideoOptions.allowedUsers field.

内容的提问来源于stack exchange,提问作者Yogesh kataria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:28:06